简体   繁体   English

从数组中获取唯一对象的更好方法

[英]Better way to get an unique object out of an array

I have an array with objects. 我有一个对象数组。 Each object got an unique id. 每个对象都有一个唯一的ID。 What is the best way to get a specific object from the array? 从数组中获取特定对象的最佳方法是什么?

Currently I use something like this 目前我使用这样的东西

  this.getObjectById = function(objectId){
    return $.grep(this.objects, function(e){ return e.id === objectId; })[0];
  }

but the fact that 但事实是

$.grep();

returns an array of results I don't know if I should go for this. 返回一个结果数组,我不知道是否应该这样做。 Because currently I take the first element of this array and it's fine because I just got one element in it. 因为当前我采用了该数组的第一个元素,所以很好,因为我只有一个元素。

But is there a more clean way? 但是还有更干净的方法吗?

Is

Array.prototype.find()

a better one? 更好的一个?

Find is faster since it returns the first match, while jquery grep loops trough entire array. Find更快,因为它返回第一个匹配项,而jquery grep循环遍历整个数组。 If you need full browser support just create you own function: 如果需要全面的浏览器支持,只需创建自己的功能即可:

this.getObjectById = function(objectId){
  for(var i = 0; i<this.objects.length; i++){
    if(objectId == this.objects[i].id) return this.objects[i];
  }
  return null;
}

使用underscore.js _.find()方法来迭代您的集合。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM