数组追加
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]])
`第二个参数是删除若干个元素,设置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]
替换数组某元素
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]
数据转换
const array = [ 1, 2, 3, 4, 5 ]
const addedArray = array.map(function(x) {
return x + 2
})
console.log(addedArray) //=> [3,4,5,6,7]
聚合函数
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
})
}
}
`或者更为抽象的方式,涉及一些函数式编程的概念`
function reduceFn(fn) {
return function(array) {
return array.reduce(fn)
}
}
网友评论