Javascript 使用下划线获取满足特定条件的元素的所有索引
我想检索满足特定条件的数组中元素的所有索引。对于ex,如果我有如下数组:Javascript 使用下划线获取满足特定条件的元素的所有索引,javascript,arrays,underscore.js,Javascript,Arrays,Underscore.js,我想检索满足特定条件的数组中元素的所有索引。对于ex,如果我有如下数组: var countries = ["India", "Australia", "United States", "Brazil"]; 我想得到字符串长度大于5的元素的索引,我应该得到一个数组,如 [2, 3] 甚至像这样的物体: { 2: "United States", 3: "Australia" } JavaScript或下划线.js中是否有我可以利用的内置/本机函数?试试这个(纯JavaScript)
var countries = ["India", "Australia", "United States", "Brazil"];
我想得到字符串长度大于5的元素的索引,我应该得到一个数组,如
[2, 3]
甚至像这样的物体:
{
2: "United States",
3: "Australia"
}
JavaScript或下划线.js中是否有我可以利用的内置/本机函数?试试这个(纯JavaScript):
在vanilla JS中,要获取索引:
var longnames = ["India", "Australia", "United States", "Brazil"]
.map( function( item, idx ){
// convert the names to indexes if name is linger than 5 characters
return ( item.length > 5) ? idx : null
}).filter(function(item){
// fiter out the nulls
return item;
});
// returns [1,2,3] since "Australia".length > 5
由于下划线同时具有.map
和.reduce
方法,因此您应该能够“下划线化”此解决方案;)
要以{index:name}
的形式创建对象,请执行以下操作:
var longnames = ["India", "Australia", "United States", "Brazil"]
.reduce( function( ret, name, idx ){
if( name.length > 5 ){
ret[ idx ] = name;
}
return ret;
}, {});
/* returns
Object { 1: "Australia", 2: "United States", 3: "Brazil" }
*/
备选方案。使用下划线减少:
var longnames = _.reduce(["India", "Australia", "United States", "Brazil"],
function( ret, name, idx ){
if( name.length > 5 ){
ret[ idx ] = name;
}
return ret;
}, {});
谢谢。。。这就是我要找的。
var longnames = ["India", "Australia", "United States", "Brazil"]
.reduce( function( ret, name, idx ){
if( name.length > 5 ){
ret[ idx ] = name;
}
return ret;
}, {});
/* returns
Object { 1: "Australia", 2: "United States", 3: "Brazil" }
*/
var longnames = _.reduce(["India", "Australia", "United States", "Brazil"],
function( ret, name, idx ){
if( name.length > 5 ){
ret[ idx ] = name;
}
return ret;
}, {});