mhe*_*ers 85 javascript underscore.js
在下划线中,我可以成功找到具有特定键值的项目
var tv = [{id:1},{id:2}]
var voteID = 2;
var data = _.find(tv, function(voteItem){ return voteItem.id == voteID; });
//data = { id: 2 }
Run Code Online (Sandbox Code Playgroud)
但是如何找到该对象发生的数组索引?
Rop*_*pez 167
findIndex 在1.8中添加:
index = _.findIndex(tv, function(voteItem) { return voteItem.id == voteID })
Run Code Online (Sandbox Code Playgroud)
请参阅:http://underscorejs.org/#findIndex
或者,如果您不介意制作另一个临时列表,这也有效:
index = _.indexOf(_.pluck(tv, 'id'), voteId);
Run Code Online (Sandbox Code Playgroud)
见:http://underscorejs.org/#pluck
las*_*ood 38
如果你想留下下划线,那么你的谓词函数可以更灵活,这里有2个想法.
由于谓词for _.find接收元素的值和索引,因此可以使用副作用来检索索引,如下所示:
var idx;
_.find(tv, function(voteItem, voteIdx){
if(voteItem.id == voteID){ idx = voteIdx; return true;};
});
Run Code Online (Sandbox Code Playgroud)
查看下划线源代码,这是如何_.find实现的:
_.find = _.detect = function(obj, predicate, context) {
var result;
any(obj, function(value, index, list) {
if (predicate.call(context, value, index, list)) {
result = value;
return true;
}
});
return result;
};
Run Code Online (Sandbox Code Playgroud)
为了使这一个findIndex功能,只需更换线路result = value;用result = index;这是同样的想法作为第一个方法.我把它包括在内,指出下划线也使用副作用来实现_.find.
spl*_*tor 34
Lo-Dash扩展了Underscore,它有findIndex方法,可以找到给定实例的索引,或者通过给定的谓词,或者根据给定对象的属性.
在你的情况下,我会这样做:
var index = _.findIndex(tv, { id: voteID });
Run Code Online (Sandbox Code Playgroud)
试试看.
tew*_*hia 28
我不知道是否存在执行此操作的现有下划线方法,但您可以使用普通javascript实现相同的结果.
Array.prototype.getIndexBy = function (name, value) {
for (var i = 0; i < this.length; i++) {
if (this[i][name] == value) {
return i;
}
}
return -1;
}
Run Code Online (Sandbox Code Playgroud)
然后你可以这样做:
var data = tv[tv.getIndexBy("id", 2)]
cra*_*tin 10
如果您的目标环境支持ES2015(或者您有一个简单的步骤,例如使用Babel),则可以使用本机Array.prototype.findIndex().
举个例子
const array = [ {id:1}, {id:2} ]
const desiredId = 2;
const index = array.findIndex(obj => obj.id === desiredId);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
151785 次 |
| 最近记录: |