首页 > 解决方案 > 第一个参数如何影响 array.map() 方法的结果?

问题描述

我在JS Bin中运行这个片段:

let array1 = [1, 4, 9, 16]
let array2=[1, 4, 9, 16]



const map1=array2.map(x=>x*2)
console.log(map1)
//Output is:[2, 8, 18, 32]


const map2 = array2.map((y,x) => x * 2)    
console.log(map2)
//Output is: [0, 2, 4, 6]

第一个参数如何影响 map 函数的输出?

编辑:两个准确的答案。只是给出我为什么问这个问题的一些背景。多亏了 SO,现在我知道第一个参数是索引处的值,而第二个是数组的索引。我在一个例子中看到了这个:map((_,x)=>itemName+=x). 如果我只传递一个参数,它会变成itemName+valueAtTheIndex,但是如果我传递两个参数并使用第二个,它会变成itemName1,itemName2,..... 相当方便!

标签: ecmascript-6

解决方案


_不影响输出.map。这是您用来进行影响输出的计算的参数。

.map(entry, index)map是在函数中使用两个 args 时的语法。

let arr = [1, 4, 9, 16]

const ret = arr.map(x => x * 2)
console.log(ret)
// Output is: [2, 8, 18, 32]

// here, x is array index - 0, 1, 2, 3
const ret = arr.map((_, x) => x * 2)
console.log(ret)
// Output is: [0, 2, 4, 6]

// try it with `_`
// You'll get the desired output
const ret = arr.map((_, x) => _ * 2)
console.log(ret)
// Output is: [2, 8, 18, 32]

推荐阅读