|
|
|
|
|
|
本文將介紹includes()檢查元素是否在數(shù)組中的 JavaScript Array 方法。
indexOf()方法的缺陷
使用數(shù)組時,你經常需要檢查數(shù)組是否包含某元素。為此,你可以使用indexOf()等方法,參考JS數(shù)組元素定位方法使用區(qū)別:indexOf()、find()和findIndex(),如下所示:
let numbers = [1,2,3];
if(numbers.indexOf(2) !== -1){
// process here
}
indexOf()方法返回數(shù)組中第一次出現(xiàn)的元素的索引。如果數(shù)組不包含元素,則indexOf()返回-1。
此外,indexOf()使用嚴格相等運算符 ( ===) 進行比較,因此,它不適用NaN,如下例所示:
[NaN].indexOf(NaN); // -1
在此示例中,數(shù)組包含一個 NaN 元素。然而,indexOf(NaN)回報-1。
includes()方法彌補了indexOf()方法的缺陷
為了解決這個問題,開發(fā)人員想出了一個輔助函數(shù)。
ECMAScript 2016 通過提供Array.prototype.includes()方法標準化了這個功能。
如果數(shù)組包含給定元素,則該includes()方法返回true;否則,它返回false。
下面說明了該includes()方法的語法:
array.includes(element,fromIndex);
includes()接受兩個參數(shù):
element可以搜索的。fromIndex是數(shù)組中搜索開始的位置。請參見以下示例:
[1,2,3].includes(2); // true
[1,2,3].includes(4); // false
[1,2,3].includes(1,1); // false
與indexOf()方法不同,includes()方法對NaN工作得非常好:
[NaN].includes(NaN); // true
請注意,includes()不區(qū)分+0和-0,如下例所示:
[-0].includes(+0); // true
includes()方法使用示例
下面的示例演示如何使用includes()方法檢查對象是否在數(shù)組中。
let bmw = {name: 'BMW' },
toyota = { name: 'Toyota'},
ford = {name: 'Ford'}
let cars = [ford, toyota];
console.log(cars.includes(ford)); // true
console.log(cars.includes(bmw)); // false在這個例子中:
首先,我們用兩個對象初始化cars數(shù)組:ford和toyota。
然后,我們使用該includes()方法檢查cars數(shù)組是否包含ford對象,在這種情況下,它返回true。
最后, bmw對象不在 cars數(shù)組中,因此includes()方法按預期返回false。
總結
在本文中,我們學習了如何使用 JavaScript Array includes()方法檢查元素是否在數(shù)組中。
相關文章
