interview-think

100 阅读1分钟

1.map函数

var new_array = arr.map(function callback(currentValue[, index[, array]]) {
 // Return element for new_array 
}[, thisArg])

参数:

  • callback 生成新数组元素的函数,使用三个参数:(函数会被自动传入下列3个参数)
    • currentValue
    • index(可选)
    • array(可选,map 方法调用的数组)
  • thisArg(可选)

Eg: ["1", "2", "3"].map(parseInt);

我们期望输出 [1, 2, 3], 而实际结果是 [1, NaN, NaN]

修改: ['1', '2', '3'].map( str => parseInt(str) )

有返回值:

map不修改调用它的原数组本身(当然可以在 callback 执行时改变原数组)

因为map生成一个新数组,当你不打算使用返回的新数组却使用map是违背设计初衷的,请用forEach或者for-of替代。你不该使用map: A)你不打算使用返回的新数组,或/且 B) 你没有从回调函数中返回值。(MDN)