2013-12-18 94 views
0

我有一個數組與對象,每個對象,一個div,有一個id。 我可以根據它的id使用它檢索給定對象的數組索引號嗎?基於數組元素id獲取數組索引號

var index = ar.map(function(el) { 
    return el. ?? 
}).indexOf('objectID4'); 
+0

可能的重複http://stackoverflow.com/q/19111224/1636522 – leaf

回答

2

像這樣:

var index = ar.map(function(el) { 
    return el.id; 
}).indexOf('objectID4'); 

工作示例:http://jsfiddle.net/bvT6B/

+0

我試過了,我得到-1。並且我知道objectID4確實存在 – user3024007

+0

@ user3024007可能區分大小寫 – thefourtheye

+0

是的,我知道...我必須弄清楚爲什麼我的實時代碼沒有使用它 – user3024007

-1

它這就是你想要什麼?

<div id="x1" class='foo'></div> 
<div id="x2" class='foo'></div> 
<div id="x3" class='foo'></div> 

<div id="res"></div> 
<script> 
function getIndexOfById(uid) { 
    var id = null; 
    $('.foo').each(function() { 
     if ($(this).attr('id') == uid) {id = $(this).index();} 
    }); 
    return id; 
} 

$('#res').html(getIndexOfById('x1') + '/' + getIndexOfById('x2') + '/' + getIndexOfById('x3')); 
</script> 

結果是

0/1/2 
+0

'$('#x1')。index( '包含.foo')'! – leaf

0

支票下面的代碼

var ar = [{'id':'objectId1','foo':'bar'},{'id':'objectId4','foo':'bar'}] 

var index = ar.map(function(el) { 
    return el.id; 
}).indexOf('objectId4'); 

alert(index); 

或者你可以在http://jsfiddle.net/VJrWc/

看看這是不是你想要的份額更多的代碼和清除你的目標。