JavaScript中經(jīng)常使用數(shù)組進(jìn)行相關(guān)的數(shù)據(jù)處理操作。愛掏網(wǎng) - it200.com其中,Array lastIndexOf()方法是比較基礎(chǔ)和常用的操作之一,用于查找給定元素在數(shù)組中最后出現(xiàn)的位置。愛掏網(wǎng) - it200.com本文將詳細(xì)介紹該方法的使用以及相關(guān)的細(xì)節(jié)問題。愛掏網(wǎng) - it200.com
lastIndexOf()方法的語法
lastIndexOf()方法具體的使用和語法如下:
array.lastIndexOf(searchElement[, fromIndex])
其中,searchElement
表示要查找的元素,fromIndex
則是起始查找位置。愛掏網(wǎng) - it200.com如果沒有設(shè)置fromIndex
,則默認(rèn)從數(shù)組末尾開始查找。愛掏網(wǎng) - it200.com該方法返回最后一個匹配的元素的位置,若沒有找到,則返回-1。愛掏網(wǎng) - it200.com
下面我們通過一些實例來說明該函數(shù)的使用方法。愛掏網(wǎng) - it200.com
示例代碼
示例一:查找某元素在數(shù)組中最后一次出現(xiàn)的位置
let arr = ["apple", "banana", "orange", "grape", "apple", "watermelon"];
let index = arr.lastIndexOf("apple");
console.log(index); // 輸出5
示例二:指定起始查找位置
let arr = ["apple", "banana", "orange", "grape", "apple", "watermelon"];
let index = arr.lastIndexOf("apple", 3);
console.log(index); // 輸出0
細(xì)節(jié)問題
1. 對于不支持indexOf的瀏覽器
在IE8及以下版本的瀏覽器中,由于其不支持lastIndexOf()方法,因此需要通過以下代碼來解決問題:
if(!Array.prototype.lastIndexOf){
Array.prototype.lastIndexOf = function(searchElement, fromIndex) {
var len = this.length;
// 在數(shù)組末尾開始查找,如果不存在搜索元素,返回-1
if (!fromIndex){
fromIndex = len - 1;
}
// 如果searchElement不存在數(shù)組中,處理后返回-1
else if (fromIndex && fromIndex < 0){
fromIndex = Math.max(0, len + fromIndex);
}
for (var i = fromIndex; i >= 0; i--) {
if (this[i] === searchElement){
return i;
}
}
// 如果未找到指定元素,則返回-1
return -1;
};
}
2. 不支持對引用類型的操作
lastIndexOf()方法不支持對引用類型的操作,例如:
let arr = [{name: "apple"}, {name: "orange"}, {name: "banana"}];
let index = arr.lastIndexOf({name: "orange"});
console.log(index); // 輸出 -1
原因是lastIndexOf()方法比較的是引用地址,所以會返回未找到的結(jié)果。愛掏網(wǎng) - it200.com如果要指定查找引用類型的方式,則需要自定義方法來實現(xiàn)。愛掏網(wǎng) - it200.com
3. 注意null或undefined的使用
lastIndexOf()方法對數(shù)組元素值為null或undefined的查找進(jìn)行了特殊處理:
let arr = [1, 2, null, undefined];
console.log(arr.lastIndexOf(null)); // 輸出2
console.log(arr.lastIndexOf(undefined)); // 輸出3
在這種情況下,lastIndexOf()方法返回的是搜索元素的非嚴(yán)格相等比較結(jié)果。愛掏網(wǎng) - it200.com
結(jié)論
本文詳細(xì)介紹了JavaScript Array lastIndexOf()方法的語法和使用方法,同時還討論了關(guān)于代碼實現(xiàn)的部分細(xì)節(jié)問題,供JavaScript程序開發(fā)人員學(xué)習(xí)和使用。愛掏網(wǎng) - it200.com