溫馨提示×

es6如何判斷數組是否包含某個元素

es6
小億
228
2023-10-07 15:03:33
欄目: 編程語言

ES6中可以使用includes()方法來判斷一個數組是否包含某個元素。這個方法返回一個布爾值,表示數組是否包含指定的元素。

語法如下:

array.includes(searchElement[, fromIndex])

參數說明:

  • searchElement:要搜索的元素。

  • fromIndex(可選):開始搜索的索引,默認為0。

示例代碼:

const array = [1, 2, 3, 4, 5];
console.log(array.includes(3));  // 輸出true
console.log(array.includes(6));  // 輸出false
console.log(array.includes(3, 2));  // 輸出false,從索引2開始搜索不包含3

注意:includes()方法在ES6中新增,如果需要兼容舊版本的瀏覽器,可以使用indexOf()方法來判斷數組是否包含某個元素。例如:

console.log(array.indexOf(3) !== -1);  // 輸出true
console.log(array.indexOf(6) !== -1);  // 輸出false

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女