---恢复内容开始---
1)判断是否是数组
[] instanceof Array
2)操作
// 添加到数组尾部 [].push('a', 'b') // 取出最后一项'b' ['a', 'b'].pop() // 取出第一项'a' ['a', 'b'].shift() // 添加到数组首部,返回数组长度,数组:['c', 'a', 'b'] ['a', 'b'].unshift('c') // 拼接, 此操作不改变原数组,返回拼接结果['a', 'b', 'c', 'd', 'e'] ['a', 'b'].contact('c', ['d', 'e'])
[1, 2, ...[3], ...[4, 5]] 返回[1, 2, 3, 4, 5] // 截取 ['a', 'b', 'c', 'd', 'e'].slice(1) // 返回 ['b', 'c', 'd', 'e'] ['a', 'b', 'c', 'd', 'e'].slice(1, 3) // 返回 ['b', 'c'],不包含第3项 // 删除第一个元素,返回['a'],数组:['b', 'c'] ['a', 'b', 'c'].splice(0, 1) // 在指定位置1上插入一个元素,不删除任何元素 ['a', 'b', 'c'].splice(1, 0, 'd') // 返回[],数组:['a', 'b', 'd', 'c'] // 替换指定位置上的元素 ['a', 'b', 'c'].splice(1, 1, 'd', 'e') // 返回['b'],数组:['a', 'd', 'e', 'c']
// 数组填充为指定值
['a', 'b', 'c'].fill(1) // 数组[1, 1, 1]
// 数组指定位置替换,参数(target, start, end(可选,默认等于数组长度)),用于处理原数组
['a', 'b', 'c', 'd', 'e'].copyWith(0, 4) // 数组['e', 'b', 'c', 'd', 'e']
3)获取位置和检测是否包含
['a', 'b', 'a'].indexOf('a') // 0,使用===判断原则 ['a', 'b', 'a'].lastIndexOf('a') // 2
['a', 'b'].includes('a') // true,ES6,更加语义化的判断数组中是否包含某个值
['a', 'b'].find(n => n === 'a') // 返回'a'
['a', 'b'].findIndex(n => n === 'a') // 返回0
4)排序
// 反序,数组['b', 'a'] ['a', 'b'].reverse() // 按字符顺序排序, 数组:[0, 1, 10, 3] [0, 1, 3, 10].sort() // 按大小排序,数组:[0, 1, 3, 10], 降序将-1和1互换 function compare (val1, val2) { return val1 < val2 ? -1 : val1 > val2 ? 1 : 0 } [0, 1, 3, 10].sort(compare)
5)迭代
// every对数组中的每一项执行function函数,如果每一项都返回true,则返回true every(function (item, index, array) {}) // some对数组中的每一项执行function函数,如果遇到有一项返回true,则返回true some(function (item, index, array) {}) // map对数组中的每一项执行function函数,将每一项的返回值作为新数组的一项,返回新数组 map(function (item, index, array) {}) // forEach对数组中的每一项执行function函数 forEach(function (item, index, array) {}) //filter对数组中的每一项执行function函数,将执行结果为true的数组项组成新的数组返回 filter(function (item, index, array) {})
//找出第一个符合条件的数组成员,没有则返回undefined
find(function (item, index, array) {})
6)ES6扩展_转换为数组
// 转换为Array Array.from() 类似数组的对象(具有length属性),例:可遍历对象(SetMap),Dom操作返回的NodeList集合,以及函数内部的arguments对象 // 将一组值转化为Array Array.of(2) // [2] new Array(2) // [ , ]
7)ES6扩展_遍历数组
keys() // 得到的是数组的index values() // 得到的是数组的值 entries() // 得到的是(index, elem)
8)数组推导(后续补充)