js中数组操作常见函数forEach,map,reduce,filter,slice

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/m0_38102188/article/details/82744536
var a = [1,22,333,4444,55555]
function Counter() {
    this.sum = 0;
}

js中操作数组的常见函数有:

  • forEach((item, index, array) => {}, thisArg)
Counter.prototype.add = function(arr) {
    arr.forEach((item, index, array) => {
        this.sum += item;
    }, this)
}
var counter = new Counter()
counter.add(a)
console.log(counter.sum)  //60355

上述方法是为了演示thisArg的用法,作为传给forEach 的回调的值this
一般来说,forEach函数仅用来遍历数组,且对数组元素的操作会影响原数组

a.forEach((item, index, array) => {
    array[index] += 1;  //这里要注意item += 1并不会起作用
})
console.log(a)  //[2, 23, 334, 4445, 55556]
  • map(function(item, index, array) => {}, thisArg)
    map函数也是遍历数组,但是它不改变原数组的值
var b = a.map((item, index, array) => {
    return item+1
})
console.log(a)  //[1,22,333,4444,55555]
console.log(b)  //[2, 23, 334, 4445, 55556]

一般map函数可以用来解析复杂数据结构,如:

var person = [
    {name: 'zyp1' , age: 18},
    {name: 'zyp2' , age: 19}
]
var names = person.map(function(item, index, array) {
    return item.name
})
console.log(names)  //['zyp1', 'zyp2']
  • reduce(function(pre, cur) {}, 0)
    reduce函数一般用来计算数组的和
var b = a.reduce((pre, cur) => {
    return pre + cur
}, 0)
console.log(b)   //60360
  • filter((item, index, array) {} , thisArg)
    filter函数一般用来作为过滤函数
var b = a.filter((item, index, array) => {
    return index >1
})
console.log(b)   //[333,4444,55555]
  • slice(begin, end)
    slice函数用来获取begin和end(不包括end)之间的数组值, 放入一个新的数组中返回
var b = a.slice(1,3)
console.log(b)  //[22,333]

猜你喜欢

转载自blog.csdn.net/m0_38102188/article/details/82744536