数组 // 空数组 let arr = Array.of() log(arr) // 数组 let arr1 = Array.of(1, 2, 3, 4, 5, 6, 7) log(arr1) 转义成数组 let p = document.querySelectorAll('p') let pArr = Array.from(p) pArr.forEach(item => { log(item.textContent) }) 遍历数组操作 // [2, 6, 10] log(Array.from([1, 3, 5], (item) => { return item * 2 })) 填充 // [7, 7, 7] log([1, '2', undefined].fill(7)) // ["a", 7, 7] 从1位置开始,一直到第3个 log(['a', 'b', 'c'].fill(7, 1, 3)) 取index和值 let arr = ['1', 'c', '3'] // 0 1 2 for (let index of arr.keys()) { log(index) } // 1 c 3 for (let value of arr.values()) { log(value) } // index对应value for (let [index, value] of arr.entries()) { log(index + ' ' + value) } 数组替换 let arr = ['q', 'w', 'e', 'r', 't'] // ["r", "w", "e", "r", "t"] // 起始位置0,要替换的值从第3个位置读取,结束位置是4 console.log(arr.copyWithin(0, 3, 4)) 查找位置 let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9] // 返回7的位置 6 console.log(arr.indexOf(7)) // 只找查询到的第一个值 4 console.log(arr.find(item => { return item > 3 })) // 返回查询到的第一个值的index console.log(arr.findIndex(item => { return item > 3 })) // 6 console.log(arr.findIndex(item => { return item === 7 })) // true console.log(arr.includes(1)) // true console.log([1, 2, NaN].includes(NaN))
reduce
let arr = [0, 1, 2, 3, 4].reduce(function (accumulator, currentValue, currentIndex, array) { // accumulator 累计器 // currentValue 当前值 // currentIndex 当前索引 // array 数组 return accumulator + currentValue }) console.log(arr)
拼接数组
let arr = ['tom', 'jerry']; let arr2 = [1, 2]; let newArr = arr.concat(arr2); console.log(newArr);
let arr = ['tom', 'jerry']; let arr2 = [1, 2]; arr.push.apply(arr, arr2); console.log(arr)
let arr = ['tom', 'jerry']; let arr2 = [1, 2]; arr.push(...arr2); console.log(arr)