1. 程式人生 > >js中陣列操作常見函式forEach,map,reduce,filter,slice

js中陣列操作常見函式forEach,map,reduce,filter,slice

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]