2017-03-01 74 views
-1

所以我一个数组,它包含两种不同的阵列:过滤器一个数组,它是另一个数组

var _staticRoutingTable = []; 

function StaticRoute(directory, extentions) { 
     this.dir = directory; 
     this.extentions = extentions; 
} 

_staticRoutingTable.push(new StaticRoute(["htmlfolder"], ["./html"])); 
_staticRoutingTable.push(new StaticRoute(["somefolder"], ["./html","./txt","./css"])); 

可以说,我只希望获得“目录” Array中的文件夹的名称是“somefolder” 。

所以我不想水木清华这样的,因为...:

return _staticRoutingTable.forEach(function callb(route) {   
     return route.dir.filter(function callb(directory) {directory=="somefolder" }) 
}); 

....我得到DIR + extention阵列。我怎样才能过滤一个数组(在这种情况下“dir”)。

+0

所以你想在完整的StaticRoute,其中this.dir =='somefolder'? – baao

+0

@baao不,我不想完整的StaticRoute,我只想返回一个数组,其中包含一个名为“somefolder”的字符串(在本例中为9 – igodie

回答

0

我还是老样子不知道我是否正确地理解你的问题 - 但要获得像['something']一个数组,你可以使用发现:

var _staticRoutingTable = []; 
 

 
function StaticRoute(directory, extentions) { 
 
    this.dir = directory; 
 
    this.extentions = extentions; 
 
} 
 

 
_staticRoutingTable.push(new StaticRoute(["htmlfolder"], ["./html"])); 
 
_staticRoutingTable.push(new StaticRoute(["somefolder"], ["./html","./txt","./css"])); 
 

 
let foo = _staticRoutingTable.find(function (a) { 
 
    return a.dir.indexOf("somefolder") > -1; 
 
}); 
 
if (foo) { 
 
    console.log(foo.dir);  
 
}

注意这将返回第一只匹配。如果您感兴趣的可能有多个匹配项,您可以切换筛选器以查找并使用生成的数组。

然而,当你正在寻找“somefolder”和想返回像['somefolder']一个数组,它会更容易只是做

console.log(['somefolder']); 

...

这适用于多个匹配:

var _staticRoutingTable = []; 
 

 
    function StaticRoute(directory, extentions) { 
 
     this.dir = directory; 
 
     this.extentions = extentions; 
 
    } 
 

 
    _staticRoutingTable.push(new StaticRoute(["htmlfolder"], ["./html"])); 
 
    _staticRoutingTable.push(new StaticRoute(["somefolder"], ["./html","./txt","./css"])); 
 

 
    let foo = _staticRoutingTable.filter(function (a) { 
 
     return a.dir.indexOf("somefolder") > -1; 
 
    }); 
 
    foo.forEach(function (v) { console.log(v.dir); });

+0

因此,这只适用于,如果数组只有一个索引值“有些文件夹“? – igodie

+0

正如我写的,如果有多个,请使用过滤器替换find @igodie – baao

+0

编辑答案@igodie – baao

相关问题