數(shù)組追加
array.push(element1[, ...[, elementN]])
const array = []
array.push(1)
console.log(array) //=> [1]
array.push(2, 3)
console.log(array) //=> [1, 2, 3]
console.log(array.length) //=> 3
首端添加
array.unshift(element1[, ...[, elementN]])
const array = [ 4, 5 ]
array.unshift(3)
console.log(array) //=> [3, 4, 5]
array.unshift(1, 2)
console.log(array) //=> [1, 2, 3, 4, 5]
插入到中間某位置
array.splice(start, deleteCount, element1[, ...[, elementN]])
`第二個參數(shù)是刪除若干個元素锹引,設(shè)置0為不刪除任何元素`
const array = [ 1, 2, 6, 7 ]
array.splice(2, 0, 3)
console.log(array) //=> [1, 2, 3, 6, 7]
array.splice(3, 0, 4, 5)
console.log(array) //=> [1, 2, 3, 4, 5, 6, 7]
刪除某位置元素
array.splice(start, deleteCount, element1[, ...[, elementN]])
const array = [1, 2, 3, 10, 4, 5]
array.splice(3, 1)
console.log(array) //=> [1, 2, 3, 4, 5]
替換數(shù)組某元素
1.
const array = [ 1, 2, 3, 4, 5 ]
array[0] = 10
console.log(array) //=> [10, 2, 3, 4, 5]
2.
const array = [ 1, 2, 3, 4, 5 ]
array.splice(1,1,6)
console.log(array) //=> [ 1, 6, 3, 4, 5 ]
過濾器
array.filter(fn)
const array = [ 1, 2, 3, 4, 5, 6, 7, 8 ]
const evenNumbers = array.filter(function(x) {
return x % 2 == 0
})
console.log(evenNumbers) //=> [2, 4, 6, 8]
數(shù)據(jù)轉(zhuǎn)換
const array = [ 1, 2, 3, 4, 5 ]
const addedArray = array.map(function(x) {
return x + 2
})
console.log(addedArray) //=> [3,4,5,6,7]
聚合函數(shù)
const array = [1,2,3,4]
1.
array.reduce((left,right) => {
return left + right
})
`針對每次所需要用到的聚合情況做些封裝`
const arrayUtils = {
function sum(array) {
return array.reduce((left,right) => {
return letf + right
})
}
function multi(array) {
return array.reduce((left,right) => {
return left * right
})
}
}
`或者更為抽象的方式吨艇,涉及一些函數(shù)式編程的概念`
function reduceFn(fn) {
return function(array) {
return array.reduce(fn)
}
}