js判斷一個數組是否包含一個指定的值


includes() 方法用來判斷一個數組是否包含一個指定的值,根據情況,如果包含則返回 true,否則返回false。

const array1 = [1, 2, 3];

console.log(array1.includes(2));
// expected output: true

const pets = ['cat', 'dog', 'bat'];

console.log(pets.includes('cat'));
// expected output: true

console.log(pets.includes('at'));
// expected output: false

https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/includes

1. array.indexOf

> 判斷數組中是否存在某個值,如果存在返回數組元素的下標,否則返回-1

```
let arr = ['something', 'anything', 'nothing', 'anything'];
let index = arr.indexOf('nothing');
# 結果:2

```

2. array.includes(searchElement[, fromIndex])

  • 判斷一個數組是否包含一個指定的值,如果存在返回 true,否則返回false。
  • 參數:searchElement需要查找的元素值。
> 參數:thisArg(可選)從該索引處開始查找 searchElement。如果為負值,則按升序從 array.length + fromIndex 的索引開始搜索。默認為 0。

```
let numbers = [12, 5, 8, 130, 44];
let result = numbers.includes(8);
# 結果: true
result = numbers.includes(118);
# 結果: false

```

3. array.find(callback[, thisArg])

  • 返回數組中滿足條件的第一個元素的值,如果沒有,返回undefined
  • 參數:callbackelement 當前遍歷到的元素。index 當前遍歷到的索引。array 數組本身。
> 參數:thisArg(可選)指定 callback 的 this 參數。

```
// ---------- 元素是普通字面值 ----------
let numbers = [12, 5, 8, 130, 44];
let result = numbers.find(item => {
    return item > 8;
});
# 結果: 12
// ---------- 元素是對象 ----------
let items = [
    {id: 1, name: 'something'},
    {id: 2, name: 'anything'},
    {id: 3, name: 'nothing'},
    {id: 4, name: 'anything'}
];
let item = items.find(item => {
    return item.id == 3;
});
# 結果: Object { id: 3, name: "nothing" }
```

4. array.findIndex(callback[, thisArg])

  • 返回數組中滿足條件的第一個元素的索引(下標), 如果沒有找到,返回-1
  • 參數:callbackelement 當前遍歷到的元素。index 當前遍歷到的索引。array 數組本身。
> 參數:thisArg(可選)指定 callback 的 this 參數。

```
// ---------- 元素是普通字面值 ----------
let numbers = [12, 5, 8, 130, 44];
let result = numbers.findIndex(item => {
    return item > 8;
});
# 結果: 0
// ---------- 元素是對象 ----------
let items = [
    {id: 1, name: 'something'},
    {id: 2, name: 'anything'},
    {id: 3, name: 'nothing'},
    {id: 4, name: 'anything'}
];
let index = items.findIndex(item => {
    return item.id == 3;
});
# 結果: 2
```


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM