首页 > 解决方案 > array.map 需要索引但不需要 currentValue

问题描述

我有一个空数组,我想用字符串填充。字符串将使用一个index值进行计数。例如:

'item 1'
'item 2'
'item 3'

我有一个工作map功能可以做到这一点:

let items  = new Array(100).fill().map((item, index) => {
 return `item ${index + 1}` 
})

虽然这确实用遍历索引值的字符串填充数组,但我也将item参数传递给map函数,即(在MDNcurrentValue中命名)。不过,我实际上并没有使用这个值。

看到这个值必须如何传递,我尝试传递null,但这给了我一个错误。我还尝试传入一个空对象,如.map(( {}, index) => ...)}. 老实说,我不知道空对象的基本原理是什么,但我想我会尝试一下。不用说,那没有用。

我的问题是——如果你对这样的必要参数没有用处,你会怎么做?我可以在那里传递某种未定义或无用的值吗?map除了执行此操作之外,我还应该使用其他功能吗?

我可以用一个for循环来做到这一点:

let items = new Array(100).fill()

for (let index = 0; index < items.length; index++ {
    items[index] = `item ${index + 1}`
}

在这种情况下,for循环会是更好的选择吗?

标签: javascriptarraysecmascript-6

解决方案


fill+map当你可以使用时是一种浪费from-

const result =
  Array.from(Array(10), (_,i) => `item ${i + 1}`)
  
console.log(result)
// [ "item 1"
// , "item 2"
// , "item 3"
// , "item 4"
// , "item 5"
// , "item 6"
// , "item 7"
// , "item 8"
// , "item 9"
// , "item 10"
// ]


推荐阅读