js遍历元素都是空的数组(因为我只需要用到索引)

问题描述

需要使用图片的路径,但是图片有很多,但是格式都是/static/pic/bg0 1 2 3 4 5

问题出现的环境背景及自己尝试过哪些方法

我尝试使用如下代码进行遍历,但是失败了

相关代码

const arr = new Array(6)
const imgsPath = arr.map((item, index) => `/static/pic/bg${index}`)

你期待的结果是什么?实际看到的错误信息又是什么?

期待imgsPath里应该是/static/pic/bg0 到5,总共6个路径字符串,但是arr.map方法并没有执行。所以最后只能写成const arr = [0, 1, 2, 3, 4, 5]来解决这个问题了。
那如果我以后有100个这种路径需要处理,怎么办呢?

阅读 3.8k
4 个回答
    (new Array(100)).fill(0).map((_, index) => `/static/pic/bg${index}`)
const imgsPath = new Array(6).fill('').map((item, index) => `/static/pic/bg${index}`);
console.log(imgsPath)

为什么非得用map,写个for循环就行了。

直接使用for循环不就好了??

const imgLen = 6
const imgsPath = []
for(let i=0;i<imgLen;i++){
    imgsPath.push(`/static/pic/bg${i}`)
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题