数组追加
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 ]
//splice(inde,howmany,item)参数 描述
//index 必需。规定从何处添加/删除元素。该参数是开始插入和(或)删除的数组元素的下标,必须是数字。
//howmany 必需。规定应该删除多少元素。必须是数字,但可以是 "0"。如果未规定此参数,则删除从 index 开始到原数组结尾的所有元素。
//item,要添加到数组的新元素
过滤器
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)
}
}
判断两个数组中一个是否完全包含另一个
isInclude (aa, bb) {
return aa.every((item) => {
return bb.some((sub) => {
return sub === item;
});
});
},
数组去重,返回新数组
isInclude (aa, bb) {
return aa.every((item) => {
return bb.some((sub) => {
return sub === item;
});
});
},