map()數組遍歷


map() 方法對數組的每個元素執行一次給定的函數。只對數組有效

特性

map()返回新數組

語法:

arr.map(callback(currentValue [, index [, array]])[, thisArg])

參數:

arr.map有三個參數,分別是:

1、arr:被遍歷的數組

2、callback(currentValue,index,array){句柄}:回調函數,該回調函數接受三個參數:

  A、currentValue:遍歷到的當前元素

  B、index:為currentValue的索引

  C、array:被遍歷的數組

3、thisArg:指代遍歷中this的值

示例:

    let arr = [1, 2,3]
    let newArr=arr.map(function (currentValue, index, ar) {
        console.log(currentValue);//遍歷打印1,2,3
        console.log(index);//遍歷打印0,1,2
        console.log(ar);//遍歷打印三次[1, 2, 3]
        console.log(this)//String {"我就是this的值"};遍歷打印三次
        return ar[index]*2
      }, "我就是this的值")
      //輸出
      console.log(arr);//[1, 2,3]           未改變源數組
      console.log(newArr);//[2, 4, 6]       返回新數組

 

 map()和forEach()的區別:

1、map()會返回新的數組,而forEach不會返回有意義的值

2、運行速度:map()>forEach()

3、是否改變源數組:map()不改變;forEach()改變


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM