2013-01-07 43 views
1

爲什麼jQuery索引在數組中返回-1?Jquery索引在搜索0時返回-1

var myArray = [0,4,8]; 
document.write('<br/>8 is at index : ' + $(myArray).index(8)); 
document.write('<br/>4 is at index : ' + $(myArray).index(4)); 
document.write('<br/>0 is at index : ' + $(myArray).index(0)); 

http://jsfiddle.net/JohnNeed/WGPMa/1/

+2

您正在不必要地使用jQuery。 –

+0

快速查看API文檔將顯示'index()'不適用於javascript數組http://api.jquery.com/index/。在$()中包裝一個數組是非常少見的,因爲'$()'通常用於DOM – charlietfl

回答

3

爲什麼在數組中的0 jQuery的指數回報-1

因爲您使用不正確。你用jQuery對象構造函數來包裝它。 jQuery希望其索引插槽包含對象(引用DOM元素),它們是truthy。所以,當你在0傳遞,這是falsy和失敗的首要條件(僅限truthy參數預期; jQuery的目的是要處理沒有傳遞的參數)。

// No argument, return index in parent 
if (!elem) { 
    return (this[ 0 ] && this[ 0 ].parentNode) ? this.first().prevAll().length : -1; 
} 

Source

如果從0(falsy)到5(truthy),it works as expected改變。

如果您想查找數組中的某些東西的索引,請在普通數組上使用indexOf()。如果你必須使用jQuery,使用$.inArray()(這確實有工作的優勢,其中Array.prototype.indexOf()不存在)。