javascript - 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
循环会是更好的选择吗?
解决方案
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"
// ]
推荐阅读
- c++ - C++ 中的 3D 运动场
- reactjs - 与 React-Native 和 React 导航一起使用时,上下文 API 返回 undefined 不是对象
- javascript - 是否可以对同一元素使用 2 种不同的字体,一种用于英语,另一种用于泰米尔语(unicode)
- python - Python中的乐透抽奖模拟
- html - 如何使图像渲染 Elm?
- python - 写入 CSV 文件时,Pandas 数据框的大小会爆炸
- python - DRF 反向找不到视图名称
- ruby-on-rails - 查看在 ruby on rails 中调用类方法?
- css - 主菜单在我的笔记本电脑上运行良好,但在手机上却不行
- java - 如何在抽屉菜单中获取登录用户的信息?