jQuery:数组索引中的元素索引

Jam*_*ead 11 javascript arrays jquery

我有一个对象数组.每个对象都具有ID属性.我想在具有特定ID的对象数组中找到索引.在jQuery中有没有优雅而简单的方法呢?

Anu*_*rag 5

See [`Array.filter`][1] to filter an array with a callback function. Each object in the array will be passed to the callback function one by one. The callback function must return `true` if the value is to be included, or false if not.

    var matchingIDs = objects.filter(function(o) {
        return o.ID == searchTerm;
    });

All objects having the ID as searchTerm will be returned as an array to matchingIDs. Get the matching element from the first index (assuming ID is unique and there's only gonna be one)

    matchingIDs[0];

  [1]: https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/filter

更新:

findIndex从ECMAScript 6 结帐.

items.findIndex(function(item) { item.property == valueToSearch; });
Run Code Online (Sandbox Code Playgroud)

由于findIndex大多数浏览器尚未提供,您可以使用此实现回填它:

if (!Array.prototype.findIndex) {
  Array.prototype.findIndex = function(predicate) {
    if (this == null) {
      throw new TypeError('Array.prototype.findIndex called on null or undefined');
    }
    if (typeof predicate !== 'function') {
      throw new TypeError('predicate must be a function');
    }
    var list = Object(this);
    var length = list.length >>> 0;
    var thisArg = arguments[1];
    var value;

    for (var i = 0; i < length; i++) {
      value = list[i];
      if (predicate.call(thisArg, value, i, list)) {
        return i;
      }
    }
    return -1;
  };
}
Run Code Online (Sandbox Code Playgroud)

  • OP询问如何获取元素的索引而不是元素本身. (2认同)

Ole*_*leg 4

在这种情况下,您应该for在 javascript 中使用循环而不是使用 jQuery。请参阅http://net.tutsplus.com/tutorials/javascript-ajax/10-ways-to-instantly-increase-your-jquery-performance/中的方法3

更新: jQuery 是用 javascript 编写的,它不可能比同样用 javascript 编写的其他代码更快。如果您使用 DOM,jQuery 非常好,但如果您使用简单的 javascript 数组或对象,jQuery 就没有太大帮助。

您正在寻找的代码可能是这样的:

for (var i=0, l = ar.length; i<l; i++) {
    if (ar[i].ID === specificID) {
        // i is the index. You can use it here directly or make a break
        // and use i after the loop (variables in javascript declared
        // in a block can be used anywhere in the same function)
        break;
    }
}
if (i<l) {
    // i is the index
}
Run Code Online (Sandbox Code Playgroud)

重要的是,您应该掌握一些简单的 javascript 规则:始终声明局部变量(不要忘记var在变量声明之前)并缓存在局部变量中多次使用的任何属性或索引(如上ar.length所示)。(例如参见http://wiki.forum.nokia.com/index.php/JavaScript_Performance_Best_Practices