Skip to content

数组扩展方法

includes()

检测数组中是否包含某个元素。

javascript
const arr = ['xiaoming', 'libai', 'anqila']

const res1 = arr.includes('xiaoming') // true

const res2 = arr.includes('sunshangxiang') // false

find()

查找数组中满足条件的那一项。

javascript
const arr = [
    {
        name: 'xiaoming',
        age: 16
    },
    {
        name: 'libai',
        age: 17
    },
    {
        name: 'anqila',
        age: 18
    }
]

const res = arr.find((item) => item.name === 'xiaoming') // {name: 'xiaoming', age: 16}

findIndex()

查找数据中满足条件的那一项的索引。

javascript
const arr = [
    {
        name: 'xiaoming',
        age: 16
    },
    {
        name: 'libai',
        age: 17
    },
    {
        name: 'anqila',
        age: 18
    }
]

const res = arr.findIndex((item) => item.name === 'xiaoming') // 0

map()

遍历数组。

javascript
const arr = ['xiaoming', 'libai', 'anqila']

arr.map((item, index) => {
    console.log(item, index) // 分别打印 xiaoming 0、libai 1、anqila 2
})

fill()

遍历数组。

javascript
new Array(3).fill('xiaoming') // ['xiaoming', 'xiaoming', 'xiaoming']

sort()

数组排序。

javascript
const arr = ['b', 'a', 'c']

const arr2 = arr.sort((a, b) => (a > b ? 1 : -1)) // ['a', 'b', 'c']

filter()

数组过滤。

javascript
const arr = ['b', 'a', 'c']

const arr2 = arr.filter((x) => x !== 'a') // ['b', 'c']

some()

判断数组中任意一项满足条件

javascript
const arr = ['b', 'a', 'c']

const res = arr.some((x) => x === 'a') // true

every()

判断数组中所有项满足条件

javascript
const arr = ['b', 'a', 'c']

const res = arr.every((x) => x === 'a') // false