第一个参数如何影响array.map()方法的结果?

时间:2018-12-17 12:18:58

标签: ecmascript-6

我正在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,..... 很方便!

3 个答案:

答案 0 :(得分:2)

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

当在.map(entry, index)函数中使用两个参数时,

map是语法。

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]

答案 1 :(得分:1)

在您的两个摘要中,您将“ x”称为两个不同的事物。在第一个x中是函数array.map() first 自变量,它将包含每个值,而在第二个片断中,x第二个参数,它将包含每个数组 index

在第一种情况下,x将包含数组值(这是您期望的值),在第二种情况下,x将包含值0、1、2、3,这将产生结果你知道了。

标识符_没有特殊含义,但是它是有效的参数标识符。您可以将其命名为y,并且会得到相同的结果。

答案 2 :(得分:1)

map函数中的第一个参数是数组中的当前值,而第二列是索引。

_用于忽略第一列。