创建数组#
// 字面量创建数组const array1 = [1, 2, 3, 4];
// Array 构造方法const array2 = new Array(); // []const array3 = new Array(3); // array3.length == 3const array4 = new Array(1, 2, 3, 'array') // [1, 2, 3, 'array]const array5 = new Array('23') // ['23'] 传入一个非数值的参数表示创建数组
// Array.of (es6) 总会创建一个包含所有传入参数的数组,而不管参数的数量与类型const array6 = Array.of(1) // [1]
// Array.from (es6) 将可迭代对象或者类数组对象转换为数组// 第一个参数为数据,第二个参数为变换函数,第三个参数为 this 绑定值
// concat (不会改变原数组) 连接两个或多个数组[1, 2, 3].concat(10, [5, 6]) // [1, 2, 3, 10, 5, 6]
// copyWithin (es6,改变原数组) 从数组的指定位置拷贝元素到数组的另一个指定位置中// 从索引 2 的位置开始粘贴,从索引 0 的位置开始复制,遇到索引 2 时停止复制[1, 2, 3, 4, 5].copyWithin(2, 0, 2) // [1, 2, 1, 2, 5]
// every 用于判断数组中每一项是否都满足条件,只有所有项都满足条件,才会返回 true[2, 4, 6].every((value, index, array) => { return value % 2})
indexOf#
返回数组中某个指定元素的下标。
第一个是需要查找的元素值(必填),第二个是开始查找元素的位置(可选)。
const array1 = [22, 3, 31, 12, 'arr'];const index = array1.indexOf(31);console.log(index); // 2
const index1 = array1.indexOf(31, 3);console.log(index1); // -1
splice#
删除元素,并返回删除的元素。
第一个是开始位置,第二个是删除数量。
const array1 = [22, 3, 31, 12];const item = array1.splice(1, 2);
console.log(item); // [3, 31]console.log(array1); // [22, 12]
filter#
创建一个新的数组,新数组中的元素是通过检查指定数组中符合条件的所有元素。
// 返回数组 ages 中所有元素都大于 18 的元素:var ages = [32, 33, 16, 40];
function checkAdult(age) { return age >= 18;}
function myFunction() { document.getElementById("demo").innerHTML = ages.filter(checkAdult);}
every#
用于判断数组中每一项是否都满足条件,只有所有项都满足条件,才会返回 true。
const array1 = [22, 3, 31, 12];
const isRight1 = array1.every((v, i, a) => { return v > 1;});
const isRight2 = array1.every((v, i, a) => { return v > 10;});
console.log(isRight1); // trueconsole.log(isRight2); // false
some#
对数组中的每一项进行判断,若都不符合则返回 false,否则返回 true
const array1 = [22, 3, 31, 12];
const isRight1 = array1.some((v, i, a) => { return v > 22;});
const isRight2 = array1.some((v, i, a) => { return v > 40;});
console.log(isRight1); // trueconsole.log(isRight2); // false
flat#
拍平数组
const array = [ [1, 2], [2, 3],];
// 拍平二维数组array.flat()[(1, 2, 2, 3)];
// 拍平任意深度的数组array.flat(Infinity);
find#
找出第一个返回值为 true 的成员
const array1 = [22, 3, 31, 12];
// value = 31const value = array1.find((v) => { return v > 22;});
findIndex#
同 find, 但是 findIndex 返回的是索引