const array = [1,2,3,4,5,6];
// array.at(index)访问index参数处的元素,当index为负数时为倒数顺序
array.at(0); // 1 第0个
array.at(2); // 3 第3个
array.at(-1); // 6 倒数第1个
// pop() 方法移除数组的最后一个元素,会改变原始数组
array.pop(); // [ 1, 2, 3, 4, 5 ]
// shift() 方法移除数组的第一项,会改变原始数组
array.shift(); // [ 2, 3, 4, 5 ]
// push() 方法向数组末尾添加新项目,并返回新长度
array.push(6); // [ 2, 3, 4, 5, 6 ]
// unshift() 方法向数组头部添加新项目,并返回新长度
array.unshift(1);
// fill() 方法用静态值填充数组中的指定元素
// 可以指定开始和结束填充的位置,如果未指定,则将填充所有元素
// array.fill(6); // [ 6, 6, 6, 6, 6, 6 ]
array.fill(6,0,2); // [ 6, 6, 3, 4, 5, 6 ]
// join() 方法将数组作为字符串返回,由指定的分隔符分隔。默认分隔符是逗号 (,)
// join() 方法不会改变原始数组
const result1 = array.join(); // string 6,6,3,4,5,6
const result2 = array.join(" and "); // 6 and 6 and 3 and 4 and 5 and 6
// reverse() 方法反转数组中元素的顺序,将改变原始数组
array.reverse();
//console.log(array); // [ 6, 5, 4, 3, 6, 6 ]
// includes() 方法确定数组是否包含指定的元素,此方法区分大小写
array.includes(6); // true
// map() 方法使用为每个数组元素调用函数的结果创建新数组,不会改变原始数组
array.map((item) => 3 * item); // [ 18, 15, 12, 9, 18, 18 ]
// find() 方法返回数组中第一个通过测试的元素的值(作为函数提供)
array.find((item) => item > 2); // 6 在数组中符合条件(>3)的第一个元素是6
// filter() 方法创建数组,其中填充了所有通过测试的数组元素(作为函数提供),不改变原始数组
array.filter((item) => item > 4); // [ 6, 5, 6, 6 ]
// every() 方法检查数组中的所有元素是否都通过了测试(被作为函数提供)
array.every((item) => item > 6); // false
// findIndex() 方法返回数组中通过测试的第一个元素的索引(作为函数提供)
array.findIndex((item) => item === 6); // 0
// reduce() 方法将数组缩减为单个值,不会改变原始数组
array.reduce((prev,curr) => prev + curr, 0); // 30
array.reduce((prev,curr) => prev + curr, 3); // 33
// array.reduce(function(total, currentValue, currentIndex, arr), initialValue)
// total 必需 initialValue,或函数先前返回的值
// currentValue 必需 当前元素的值
// index 可选 当前元素的数组索引
// arr 可选 当前元素所属的数组对象
// initialValue 可选 作为初始值传递给函数的
最后修改:2023 年 08 月 22 日
© 允许规范转载