鍍金池/ 問(wèn)答/HTML/ js遍歷元素都是空的數(shù)組(因?yàn)槲抑恍枰玫剿饕?

js遍歷元素都是空的數(shù)組(因?yàn)槲抑恍枰玫剿饕?

問(wèn)題描述

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

問(wèn)題出現(xiàn)的環(huán)境背景及自己嘗試過(guò)哪些方法

我嘗試使用如下代碼進(jìn)行遍歷,但是失敗了

相關(guān)代碼

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

你期待的結(jié)果是什么?實(shí)際看到的錯(cuò)誤信息又是什么?

期待imgsPath里應(yīng)該是/static/pic/bg0 到5,總共6個(gè)路徑字符串,但是arr.map方法并沒(méi)有執(zhí)行。所以最后只能寫(xiě)成const arr = [0, 1, 2, 3, 4, 5]來(lái)解決這個(gè)問(wèn)題了。
那如果我以后有100個(gè)這種路徑需要處理,怎么辦呢?

回答
編輯回答
枕邊人

為什么非得用map,寫(xiě)個(gè)for循環(huán)就行了。

2018年5月24日 12:52
編輯回答
怪痞

直接使用for循環(huán)不就好了??

const imgLen = 6
const imgsPath = []
for(let i=0;i<imgLen;i++){
    imgsPath.push(`/static/pic/bg${i}`)
}
2017年9月6日 01:52
編輯回答
瘋浪
    (new Array(100)).fill(0).map((_, index) => `/static/pic/bg${index}`)
2018年4月5日 05:43
編輯回答
柚稚
const imgsPath = new Array(6).fill('').map((item, index) => `/static/pic/bg${index}`);
console.log(imgsPath)
2018年5月16日 10:07