ecmascript-6 - 第一个参数如何影响 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,.....
相当方便!
解决方案
_
不影响输出.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]
推荐阅读
- android - Android Studio - 每次创建新活动时都会出错
- gtk - 为什么 gtk_render_check 结果不是我所期望的?
- javascript - PHP验证不刷新
- python - 将 SERVING 元标记添加到 TensorFlow 中的冻结模型
- r - 如何在R中找到HH:MM(一天中的时间)的平均值?
- ios - 试飞崩溃
- sql-server - SQL Server:帐户需要访问另一个数据库中的数据
- javascript - ReactJS - 无法读取未定义的属性“preventDefault”
- python - 让 VSCode 了解应用程序内置
- google-sheets - 使用查询语句根据日期过滤结果(谷歌表格)