繁体   English   中英

array.map需要索引,但不需要currentValue

[英]array.map needs index but doesn't need currentValue

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

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

我有一个可以执行此操作的map功能:

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

虽然这确实用迭代索引值的字符串填充了数组,但我也将item参数传递给map函数,即currentValue (在MDN中命名)。 我实际上并没有使用此值。

看到该值必须如何传递,我试图传递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循环会是更好的选择吗?

当您仅可以from使用时, fill + map是一种浪费

 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" // ] 

引用您的代码

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

item将是“ undefined”,是的,您需要传递item(currentValue),因为它是必填字段。

只需一行即可实现:

let items  = Array.from(Array(100).keys()).map( item => `item ${item+1}`);

没有地图

let items  = Array.from(Array(100).keys(), item => `item ${item+1}`);

您无需担心未使用的参数。 如果您真的介意,请尝试以下代码:

 var items = new Array(...new Array(100).keys()).map(index => { return `item ${index + 1}` }); console.log(items); 

未使用的参数应分配给_

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM