JS 数组速查表
简短的 JavaScript 数组方法备忘单,可帮助您学习、提醒或准备 JS 面试。
['a', 'b', 'c'].length // 3
['a', 'b', 'c'].concat(['d', 'e']) // ['a', 'b', 'c', 'd', 'e']
['a', 'b', 'c'].join('_') // 'a_b_c'
['a', 'b', 'c'].slice(2) // ['c']
['a', 'b', 'c', 'b', 'b'].indexOf('b') // 1
['a', 'b', 'c', 'b', 'b'].lastIndexOf('b') // 4
[1, 2, 3, 4].map(item => item * 10) // [10, 20, 30, 40]
[1, 2, 3, 4].reduce((sum, cur) => sum + cur) // 10
[4, 2, 5, 1, 3].sort() // [1, 2, 3, 4, 5]
['a', 'b', 'c'].reverse() // ['c', 'b', 'a']
[1, 2, 3, 4].forEach(item => console.log(item))
[1, 2, 3, 4].every(item => item > 0) // true
[-1, -2, -3, 4].some(item => item > 0) // true
[1, -1, 2, -2, 3].filter(item => item > 0) // [1, 2, 3]
[1, 2, 3].shift() // 1; and base array = [2, 3]
[1, 2, 3].unshift(4, 5) // [4, 5, 1, 2, 3]
[1, 2, 3].pop() // 3; base array - [1, 2]
[1, 2, 3].push(4, 5) // 5; base array - [1, 2, 3, 4, 5]
["I'm", "learning", "JavaScript"].splice(1, 1) // ["learning"]; ["I'm", "JavaScript"]
长度
返回数组中元素的总数
['a', 'b', 'c'].length // 3
连接
此方法将基础数组与参数数组合并。Concat 不会更改现有的基础数组,只会返回新的
数组。
['a', 'b', 'c'].concat(['d', 'e']) // ['a', 'b', 'c', 'd', 'e']
// or you can merge arrays without any method (by spread operator)
const arr1 = ['a', 'b', 'c']
const arr2 = ['d', 'e']
const result = [...arr1, ...arr2] // ['a', 'b', 'c', 'd', 'e']
加入
返回数组元素的字符串,这些元素由参数中的分隔符字符串分隔。
['a', 'b', 'c'].join('_') // 'a_b_c'
片
start
返回来自和end
来自参数的数组副本
['a', 'b', 'c'].slice(2) // ['c']
['a', 'b', 'c'].slice(0, 1) // ['a']
索引
返回第一个找到的元素的索引
['a', 'b', 'c', 'b', 'b'].indexOf('b') // 1
['a', 'b', 'c'].indexOf('d') // -1
lastIndexOf
返回最后找到的元素的索引
['a', 'b', 'c', 'b', 'b'].lastIndexOf('b') // 4
地图
方法创建一个新数组,其中包含调用提供的回调的结果
[1, 2, 3, 4].map(item => item * 10) // [10, 20, 30, 40]
减少
该方法对数组的每个元素执行回调(来自参数),从而产生单个输出值。
[1, 2, 3, 4].reduce((sum, cur) => sum + cur) // 10
种类
返回排序后的数组
[4, 2, 5, 1, 3].sort() // [1, 2, 3, 4, 5]
[4, 2, 5, 1, 3].sort((a, b) => b - a) // [5, 4, 3, 2, 1]
撤销
方法反转数组
['a', 'b', 'c'].reverse() // ['c', 'b', 'a']
forEach
该方法对每个数组元素执行一次提供的函数。
[1, 2, 3, 4].forEach(item => console.log(item))
每一个
true
如果回调true
为每个数组元素返回,则返回。
[1, 2, 3, 4].every(item => item > 0) // true
一些
true
如果回调返回true
任何数组元素,则返回。
[-1, -2, -3, 4].some(item => item > 0) // true
筛选
该方法创建一个新数组,其中包含通过提供的回调实现的测试的所有元素。
[1, -1, 2, -2, 3].filter(item => item > 0) // [1, 2, 3]
转移
从数组中删除第一个元素
[1, 2, 3].shift() // 1; and base array = [2, 3]
取消移位
将元素添加到数组的开头
[1, 2, 3].unshift(4, 5) // 5; array - [4, 5, 1, 2, 3]
流行音乐
从数组中删除最后一个元素并返回该元素。
[1, 2, 3].pop() // 3; base array - [1, 2]
推
该方法将一个或多个元素添加到数组的末尾
[1, 2, 3].push(4, 5) // 5; base array - [1, 2, 3, 4, 5]
拼接
该方法通过删除或替换现有元素和/或在适当位置添加新元素来更改数组的内容。
let arr = ["I'm", "learning", "JavaScript"];
arr.splice(1, 1); // from index 1, delete 1 element
console.log( arr ); // ["I'm", "JavaScript"]
如果你喜欢这篇文章,请点击“赞”并添加到书签。也可以在Twitter上关注我。
文章来源:https://dev.to/sakhnyuk/js-array-cheatsheet-31h0