2010-07-13 76 views
11

我有一個對象數組。每個對象都有一個ID屬性。我想在具有特定ID的對象的數組中找到索引。有沒有在jQuery中做到這一點的優雅和簡單的方法?jQuery:數組中元素的索引,其中謂詞

+0

準確地說,我也在尋找。太糟糕了沒有優雅的解決方案確實... – epeleg 2012-07-18 20:45:34

回答

4

在這種情況下,您應該在javascript中使用for循環,而不是使用jQuery。見路3 http://net.tutsplus.com/tutorials/javascript-ajax/10-ways-to-instantly-increase-your-jquery-performance/

更新: 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 
} 

重要的是你應該持有一些簡單的JavaScript規則:始終聲明局部變量(不要忘了var變量聲明之前)和緩存您在本地變量中使用多次的任何屬性或索引(如上面的ar.length)。 (參見例如http://wiki.forum.nokia.com/index.php/JavaScript_Performance_Best_Practices

3

不是真的優雅,但一個可愛的把戲:

var index = parseInt(
    $.map(array, function(i, o) { return o.id === target ? i : ''; }).join('') 
); 

的jQuery沒有很多這樣的功能性結構的;圖書館的哲學着重於DOM爭奪的工作。他們甚至不會添加一個.reduce()函數,因爲沒有人能想到它對核心功能有用的原因。

Underscore.js庫有很多這樣的工具,它用jQuery「很好玩」。

+0

不錯,但效率低下,因爲它遍歷了數組中的所有元素... 如果你仔細研究它們,你可能也會建立一個反向散列,這樣你就可以回答Q 「specificID」 S。 – epeleg 2012-07-18 20:48:01

+0

@eleleg很好,很清楚。 – Pointy 2012-07-18 20:55:50

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; }); 

由於findIndex不適用於大多數瀏覽器還沒有,你可以回填它使用這implementation

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; 
    }; 
} 
+2

OP詢問如何獲取元素的索引而不是元素本身。 – epeleg 2012-07-18 20:43:26

+0

@epeleg - 我沒有看到正確的問題。在Oleg建議的情況下,通過每個物體循環並在發現匹配時打破。 – Anurag 2012-07-19 00:05:58

0

使用j訂購。 http://github.com/danstocker/jorder

將您的數組放入jOrder表中,並在'ID'字段中添加一個索引。

var table = jOrder(data) 
    .index('id', ['ID']); 

然後,通過獲取元素的數組索引:

var arrayidx = table.index('id').lookup([{ ID: MyID }]); 

如果你想整行,則:

var filtered = table.where([{ ID: MyID }]); 

瞧。

1

有沒有內置的方法,該[].indexOf()方法不採取謂詞,因此你需要一些定製:

function indexOf(array, predicate) 
{ 
    for (var i = 0, n = array.length; i != n; ++i) { 
     if (predicate(array[i])) { 
      return i; 
     } 
    } 
    return -1; 
} 

var index = indexOf(arr, function(item) { 
    return item.ID == 'foo'; 
}); 

函數返回-1如果斷言永遠不會產生一個truthy值。