主题
Array 实例方法
提示
❗ 表示会修改原数组,使用时请小心。
at()
at()
方法接收一个整数值并返回该索引对应的元素,允许正数和负数。负整数从数组中的最后一个元素开始倒数。
语法:
js
at(index)
示例
js
const array1 = [5, 12, 8, 130, 44]
let index = 2
console.log(`An index of ${index} returns ${array1.at(index)}`)
// => "An index of 2 returns 8"
index = -2
console.log(`An index of ${index} returns ${array1.at(index)}`)
// => "An index of -2 returns 130"
concat()
concat()
方法用于合并两个或多个数组。此方法不会更改现有数组,而是返回一个新数组。
语法:
js
concat()
concat(value0)
concat(value0, value1)
concat(value0, value1, /* … ,*/ valueN)
示例
js
const array1 = ['a', 'b', 'c']
const array2 = ['d', 'e', 'f']
const array3 = array1.concat(array2)
console.log(array3)
// => Array ["a", "b", "c", "d", "e", "f"]
❗copyWithin()
copyWithin()
方法浅复制数组的一部分到同一数组中的另一个位置,并返回它,不会改变原数组的长度。
语法:
js
copyWithin(target)
copyWithin(target, start)
copyWithin(target, start, end)
示例
js
const array1 = ['a', 'b', 'c', 'd', 'e']
// Copy to index 0 the element at index 3
console.log(array1.copyWithin(0, 3, 4))
// => Array ["d", "b", "c", "d", "e"]
// Copy to index 1 all elements from index 3 to the end
console.log(array1.copyWithin(1, 3))
// => Array ["d", "d", "e", "d", "e"]
entries()
entries()
方法返回一个新的数组迭代器对象,该对象包含数组中每个索引的键/值对。
语法:
js
entries()
示例
js
const array1 = ['a', 'b', 'c']
const iterator1 = array1.entries()
console.log(iterator1.next().value)
// => Array [0, "a"]
console.log(iterator1.next().value)
// => Array [1, "b"]
every()
every()
方法测试一个数组内的所有元素是否都能通过指定函数的测试。它返回一个布尔值。
语法:
js
every(callbackFn)
every(callbackFn, thisArg)
示例
js
const isBelowThreshold = currentValue => currentValue < 40
const array1 = [1, 30, 39, 29, 10, 13]
console.log(array1.every(isBelowThreshold))
// => true
❗fill()
fill()
方法用一个固定值填充一个数组中从起始索引(默认为 0)到终止索引(默认为 array.length)内的全部元素。它返回修改后的数组。
语法:
js
fill(value)
fill(value, start)
fill(value, start, end)
示例
js
const array1 = [1, 2, 3, 4]
// Fill with 0 from position 2 until position 4
console.log(array1.fill(0, 2, 4))
// => Array [1, 2, 0, 0]
// Fill with 5 from position 1
console.log(array1.fill(5, 1))
// => Array [1, 5, 5, 5]
console.log(array1.fill(6))
// => Array [6, 6, 6, 6]
Array.from({ length: 3 }).fill(1)
// => [1, 1, 1]
filter()
filter()
方法创建给定数组一部分的浅拷贝,其包含通过所提供函数实现的测试的所有元素。
语法:
js
filter(callbackFn)
filter(callbackFn, thisArg)
示例
js
const words = ['spray', 'elite', 'exuberant', 'destruction', 'present']
const result = words.filter(word => word.length > 6)
console.log(result)
// => Array ["exuberant", "destruction", "present"]
find()
find()
方法返回数组中满足提供的测试函数的第一个元素的值。否则返回 undefined
。
提示
- 如果需要查找数组中最后一个匹配的元素,使用
findLast()
。 - 如果需要在数组中找到对应元素的索引,请使用
findIndex()
。 - 如果需要查找数组中最后一个匹配元素的索引,使用
findLastIndex()
。 - 如果需要查找某个值的索引,请使用
indexOf()
。(它类似于findIndex()
,但只是检查每个元素是否与值相等,而不是使用测试函数。) - 如果需要查找数组中是否存在某个值,请使用
includes()
。同样,它检查每个元素是否与值相等,而不是使用测试函数。 - 如果需要查找是否有元素满足所提供的测试函数,请使用
some()
。 - 如果需要查找每个元素都满足所提供的测试函数,请使用
every()
。
语法:
js
find(callbackFn)
find(callbackFn, thisArg)
示例
js
const array1 = [5, 12, 8, 130, 44]
const found = array1.find(element => element > 10)
console.log(found)
// => 12
findIndex()
findIndex()
方法返回数组中满足提供的测试函数的第一个元素的索引。若没有找到对应元素则返回 -1
。
语法:
js
findIndex(callbackFn)
findIndex(callbackFn, thisArg)
示例
js
const array1 = [5, 12, 8, 130, 44]
const isLargeNumber = element => element > 13
console.log(array1.findIndex(isLargeNumber))
// => 3
findLast() ES2022
findLast()
方法反向迭代数组,并返回满足提供的测试函数的第一个元素的值。如果没有找到对应元素,则返回 undefined。
语法:
js
findLast(callbackFn)
findLast(callbackFn, thisArg)
示例
js
const array1 = [5, 12, 50, 130, 44]
const found = array1.findLast(element => element > 45)
console.log(found)
// => 130
考虑到兼容性问题时,可替换为:
js
shapes.findLast()
// =>
shapes.slice().reverse().find()
findLastIndex() ES2022
findLastIndex()
方法反向迭代数组,并返回满足所提供的测试函数的第一个元素的索引。若没有找到对应元素,则返回 -1。
语法:
js
findLastIndex(callbackFn)
findLastIndex(callbackFn, thisArg)
示例
js
const array1 = [5, 12, 50, 130, 44]
const isLargeNumber = element => element > 45
console.log(array1.findLastIndex(isLargeNumber))
// => 3
// Index of element with value: 130
flat()
flat()
方法创建一个新的数组,并根据指定深度递归地将所有子数组元素拼接到新的数组中。
语法:
js
flat()
flat(depth)
示例
js
const arr1 = [0, 1, 2, [3, 4]]
console.log(arr1.flat())
// => Array [0, 1, 2, 3, 4]
const arr2 = [0, 1, [2, [3, [4, 5]]]]
console.log(arr2.flat())
// => Array [0, 1, 2, Array [3, Array [4, 5]]]
console.log(arr2.flat(2))
// => Array [0, 1, 2, 3, Array [4, 5]]
console.log(arr2.flat(Infinity))
// => Array [0, 1, 2, 3, 4, 5]
flatMap()
flatMap()
方法对数组中的每个元素应用给定的回调函数,然后将结果展开一级,返回一个新数组。
提示
它等价于在调用 map()
方法后再调用深度为 1 的 flat()
方法(arr.map(...args).flat()
),但比分别调用这两个方法稍微更高效一些。
语法:
js
flatMap(callbackFn)
flatMap(callbackFn, thisArg)
示例
js
const arr1 = [1, 2, 1]
const result = arr1.flatMap(num => (num === 2 ? [2, 2] : 1))
console.log(result)
// => Array [1, 2, 2, 1]
forEach()
forEach()
方法对数组的每个元素执行一次给定的函数。
语法:
js
forEach(callbackFn)
forEach(callbackFn, thisArg)
示例
js
const array1 = ['a', 'b', 'c']
array1.forEach(element => console.log(element))
// => "a"
// => "b"
// => "c"
includes()
includes()
方法用来判断一个数组是否包含一个指定的值,根据情况,如果包含则返回 true,否则返回 false。
语法:
js
includes(searchElement)
includes(searchElement, fromIndex)
示例
js
const array1 = [1, 2, 3]
console.log(array1.includes(2))
// => true
const pets = ['cat', 'dog', 'bat']
console.log(pets.includes('cat'))
// => true
console.log(pets.includes('at'))
// => false
indexOf()
indexOf()
方法返回数组中第一次出现给定元素的下标,如果不存在则返回 -1
。
语法:
js
indexOf(searchElement)
indexOf(searchElement, fromIndex)
示例
js
const beasts = ['ant', 'bison', 'camel', 'duck', 'bison']
console.log(beasts.indexOf('bison'))
// => 1
// Start from index 2
console.log(beasts.indexOf('bison', 2))
// => 4
console.log(beasts.indexOf('giraffe'))
// => -1
join()
join()
方法将一个数组(或一个类数组对象)的所有元素连接成一个字符串并返回这个字符串,用逗号或指定的分隔符字符串分隔。如果数组只有一个元素,那么将返回该元素而不使用分隔符。
语法:
js
join()
join(separator)
提示
- 如果省略,数组元素用逗号(
,
)分隔。 - 如果
separator
是空字符串(""
),则所有元素之间都没有任何字符。
示例
js
const elements = ['Fire', 'Air', 'Water']
console.log(elements.join())
// => "Fire,Air,Water"
console.log(elements.join(''))
// => "FireAirWater"
console.log(elements.join('-'))
// => "Fire-Air-Water"
keys()
keys()
方法返回一个新的数组迭代器对象,其中包含数组中每个索引的键。
语法:
js
keys()
示例
js
const array1 = ['a', 'b', 'c']
const iterator = array1.keys()
for (const key of iterator) {
console.log(key)
}
// => 0
// => 1
// => 2
lastIndexOf()
lastIndexOf()
方法返回数组中给定元素最后一次出现的索引,如果不存在则返回 -1。该方法从 fromIndex 开始向前搜索数组。
语法:
js
lastIndexOf(searchElement)
lastIndexOf(searchElement, fromIndex)
示例
js
const animals = ['Dodo', 'Tiger', 'Penguin', 'Dodo']
console.log(animals.lastIndexOf('Dodo'))
// => 3
console.log(animals.lastIndexOf('Tiger'))
// => 1
map()
map()
方法创建一个新数组,这个新数组由原数组中的每个元素都调用一次提供的函数后的返回值组成。
语法:
js
map(callbackFn)
map(callbackFn, thisArg)
示例
js
const array1 = [1, 4, 9, 16]
// Pass a function to map
const map1 = array1.map(x => x * 2)
console.log(map1)
// => Array [2, 8, 18, 32]
提示
如果在 map()
的测试函数中返回 undefined
/ null
,该子项的值也为 undefined
/ null
,并不会直接过滤出去。
若需要过滤一些子项时,map
可配合 filter
一起使用,或者直接使用 reduce
一步到位。
js
const ids = []
for (const o of objs) {
if (o.id) ids.push(o.id)
}
js
const ids = objs.filter(o => o.id).map(o => o.id)
js
const ids = objs.reduce((acc, o) => {
if (o.id) acc.push(o.id)
return acc
}, [])
❗pop()
pop()
方法从数组中删除最后一个元素,并返回该元素的值。此方法会更改数组的长度。
语法:
js
pop()
示例
js
const plants = ['broccoli', 'cauliflower', 'cabbage', 'kale', 'tomato']
console.log(plants.pop())
// => "tomato"
console.log(plants)
// => Array ["broccoli", "cauliflower", "cabbage", "kale"]
plants.pop()
console.log(plants)
// => Array ["broccoli", "cauliflower", "cabbage"]
❗push()
push()
方法将指定的元素添加到数组的末尾,并返回新的数组长度。
语法:
js
push()
push(element0)
push(element0, element1)
push(element0, element1, /* … ,*/ elementN)
示例
js
const animals = ['pigs', 'goats', 'sheep']
const count = animals.push('cows')
console.log(count)
// => 4
console.log(animals)
// => Array ["pigs", "goats", "sheep", "cows"]
animals.push('chickens', 'cats', 'dogs')
console.log(animals)
// => Array ["pigs", "goats", "sheep", "cows", "chickens", "cats", "dogs"]
reduce()
reduce()
方法对数组中的每个元素按序执行一个提供的 reducer 函数,每一次运行 reducer 会将先前元素的计算结果作为参数传入,最后将其结果汇总为单个返回值。
第一次执行回调函数时,不存在“上一次的计算结果”。如果需要回调函数从数组索引为 0 的元素开始执行,则需要传递初始值。否则,数组索引为 0 的元素将被用作初始值,迭代器将从第二个元素开始执行(即从索引为 1 而不是 0 的位置开始)。
语法:
js
reduce(callbackFn)
reduce(callbackFn, initialValue)
示例
js
const array1 = [1, 2, 3, 4]
// 0 + 1 + 2 + 3 + 4
const initialValue = 0
const sumWithInitial = array1.reduce((accumulator, currentValue) => accumulator + currentValue, initialValue)
console.log(sumWithInitial)
// => 10
reduceRight()
reduceRight()
方法对累加器(accumulator)和数组的每个值(按从右到左的顺序)应用一个函数,并使其成为单个值。
语法:
js
reduceRight(callbackFn)
reduceRight(callbackFn, initialValue)
示例
js
const array1 = [
[0, 1],
[2, 3],
[4, 5],
]
const result = array1.reduceRight((accumulator, currentValue) => accumulator.concat(currentValue))
console.log(result)
// => Array [4, 5, 2, 3, 0, 1]
❗reverse()
reverse()
方法就地反转数组中的元素,并返回同一数组的引用。数组的第一个元素会变成最后一个,数组的最后一个元素变成第一个。换句话说,数组中的元素顺序将被翻转,变为与之前相反的方向。
语法:
js
reverse()
示例
js
const array1 = ['one', 'two', 'three']
console.log('array1:', array1)
// => "array1:" Array ["one", "two", "three"]
const reversed = array1.reverse()
console.log('reversed:', reversed)
// => "reversed:" Array ["three", "two", "one"]
// Careful: reverse is destructive -- it changes the original array.
console.log('array1:', array1)
// => "array1:" Array ["three", "two", "one"]
❗shift()
shift()
方法从数组中删除第一个元素,并返回该元素的值。此方法更改数组的长度。
语法:
js
shift()
示例
js
const array1 = [1, 2, 3]
const firstElement = array1.shift()
console.log(array1)
// => Array [2, 3]
console.log(firstElement)
// => 1
slice()
slice()
方法返回一个新的数组对象,这一对象是一个由 start 和 end 决定的原数组的浅拷贝(包括 start,不包括 end),其中 start 和 end 代表了数组元素的索引。原始数组不会被改变。
语法:
js
slice()
slice(start)
slice(start, end)
示例
js
const animals = ['ant', 'bison', 'camel', 'duck', 'elephant']
console.log(animals.slice(2))
// => Array ["camel", "duck", "elephant"]
console.log(animals.slice(2, 4))
// => Array ["camel", "duck"]
console.log(animals.slice(1, 5))
// => Array ["bison", "camel", "duck", "elephant"]
console.log(animals.slice(-2))
// => Array ["duck", "elephant"]
console.log(animals.slice(2, -1))
// => Array ["camel", "duck"]
console.log(animals.slice())
// => Array ["ant", "bison", "camel", "duck", "elephant"]
some()
some()
方法测试数组中是否至少有一个元素通过了由提供的函数实现的测试。如果在数组中找到一个元素使得提供的函数返回 true,则返回 true;否则返回 false。它不会修改数组。
语法:
js
some(callbackFn)
some(callbackFn, thisArg)
示例
js
const array = [1, 2, 3, 4, 5]
// Checks whether an element is even
const even = element => element % 2 === 0
console.log(array.some(even))
// => true
❗sort()
sort()
方法就地对数组的元素进行排序,并返回对相同数组的引用。默认排序是将元素转换为字符串,然后按照它们的 UTF-16 码元值升序排序。
语法:
js
sort()
sort(compareFn)
示例
js
const months = ['March', 'Jan', 'Feb', 'Dec']
months.sort()
console.log(months)
// => Array ["Dec", "Feb", "Jan", "March"]
const array1 = [1, 30, 4, 21, 100000]
array1.sort()
console.log(array1)
// => Array [1, 100000, 21, 30, 4]
❗splice()
splice()
方法就地移除或者替换已存在的元素和/或添加新的元素。
语法:
js
splice(start)
splice(start, deleteCount)
splice(start, deleteCount, item1)
splice(start, deleteCount, item1, item2)
splice(start, deleteCount, item1, item2, /* …, */ itemN)
示例
js
const months = ['Jan', 'March', 'April', 'June']
months.splice(1, 0, 'Feb')
// Inserts at index 1
console.log(months)
// => Array ["Jan", "Feb", "March", "April", "June"]
months.splice(4, 1, 'May')
// Replaces 1 element at index 4
console.log(months)
// => Array ["Jan", "Feb", "March", "April", "May"]
toLocaleString()
toLocaleString()
方法返回一个字符串,表示数组中的所有元素。每个元素通过调用它们自己的 toLocaleString 方法转换为字符串,并且使用特定于语言环境的字符串(例如逗号“,”)分隔开。
语法:
js
toLocaleString()
toLocaleString(locales)
toLocaleString(locales, options)
示例
js
const array1 = [1, 'a', new Date('21 Dec 1997 14:12:00 UTC')]
const localeString = array1.toLocaleString('en', { timeZone: 'UTC' })
console.log(localeString)
// => "1,a,12/21/1997, 2:12:00 PM",
// This assumes "en" locale and UTC timezone - your results may vary
toReversed() 2023 NEW
toReversed()
方法是 reverse()
方法对应的复制版本。它返回一个元素顺序相反的新数组。
语法:
js
toReversed()
示例
js
const items = [1, 2, 3]
const reversedItems = items.toReversed()
console.log(reversedItems) // [3, 2, 1]
toSorted() 2023 NEW
toSorted()
方法是 sort()
方法的复制方法版本。它返回一个新数组,其元素按升序排列。
语法:
js
// 不传入函数
toSorted()
// 传入箭头函数
toSorted((a, b) => {})
// 传入比较函数
toSorted(compareFn)
// 內联比较函数
toSorted(function compareFn(a, b) {})
示例
js
const months = ['Mar', 'Jan', 'Feb', 'Dec']
const sortedMonths = months.toSorted()
console.log(sortedMonths) // ['Dec', 'Feb', 'Jan', 'Mar']
const values = [1, 10, 21, 2]
const sortedValues = values.toSorted((a, b) => a - b)
console.log(sortedValues) // [1, 2, 10, 21]
toSpliced() 2023 NEW
toSpliced()
方法是 splice()
方法的复制版本。它返回一个新数组,并在给定的索引处删除和/或替换了一些元素。
语法:
js
toSpliced(start)
toSpliced(start, deleteCount)
toSpliced(start, deleteCount, item1)
toSpliced(start, deleteCount, item1, item2, itemN)
示例
js
const months = ['Jan', 'Mar', 'Apr', 'May']
// 在索引 1 处添加一个元素
const months2 = months.toSpliced(1, 0, 'Feb')
console.log(months2) // ["Jan", "Feb", "Mar", "Apr", "May"]
// 从第 2 个索引开始删除两个元素
const months3 = months2.toSpliced(2, 2)
console.log(months3) // ["Jan", "Feb", "May"]
// 在索引 1 处用两个新元素替换一个元素
const months4 = months3.toSpliced(1, 1, 'Feb', 'Mar')
console.log(months4) // ["Jan", "Feb", "Mar", "May"]
// 原数组不会被修改
console.log(months) // ["Jan", "Mar", "Apr", "May"]
toString()
toString() 方法返回一个字符串,表示指定的数组及其元素。
js
const array1 = [1, 2, 'a', '1a']
console.log(array1.toString())
// => "1,2,a,1a"
❗unshift()
unshift()
方法将指定元素添加到数组的开头,并返回数组的新长度。
语法:
js
unshift()
unshift(element1)
unshift(element1, element2)
unshift(element1, element2, /* …, */ elementN)
示例
js
const array1 = [1, 2, 3]
console.log(array1.unshift(4, 5))
// => 5
console.log(array1)
// => Array [4, 5, 1, 2, 3]
values()
values()
方法返回一个新的数组迭代器对象,该对象迭代数组中每个元素的值。
语法:
js
values()
示例
js
const array1 = ['a', 'b', 'c']
const iterator = array1.values()
for (const value of iterator) {
console.log(value)
}
// => "a"
// => "b"
// => "c"
with() 2023 NEW
with()
方法是使用方括号表示法修改指定索引值的复制方法版本。它会返回一个新数组,其指定索引处的值会被新值替换。
语法:
js
arrayInstance.with(index, value)
示例
js
const arr = [1, 2, 3, 4, 5]
console.log(arr.with(2, 6)) // [1, 2, 6, 4, 5]
console.log(arr) // [1, 2, 3, 4, 5]