提问人:Adam Hunter 提问时间:11/14/2023 最后编辑:blackgreenAdam Hunter 更新时间:11/14/2023 访问量:82
JavaScript 中的动态变量名称 [duplicate]
Dynamic Variable Name In JavaScript [duplicate]
问:
我正在尝试做一个循环函数,它将从数组中获取歌词诗句。我确实有一个工作函数,但没有动态变量。我想要的只是某种程度上的动态 var 名称。在数组项中,有从“ve1”到“ve20”的值。 所以我需要得到这个 ve[i] 就像下面显示的那样,但它没有按照它应该的方式工作。
function testingLyrics(){
for (let i = 0; i < allMusic[indexNumb - 1].lyrics.length; i++) {
if(allMusic[indexNumb - 1].lyrics.ve[i].stamp){
/* Action */
}}
}
数组如下所示
var allMusic = [
{
lyrics:{
ve1:{
ls: "The club isn't the best place to find a lover",
},
ve2:{
ls: "So the bar is where I go",
},
ve3:{
ls: "Me and my friends at the table doing shots",
},
},
},
{
lyrics:{
ve1:{
ls: "I've been having a good time",
},
ve2:{
ls: "Man, I feel just like a rockstar (ayy, ayy)",
},
ve3:{
ls: "All my brothers got that gas",
},
},
},
]
答:
2赞
Omar Khaled
11/14/2023
#1
通过这种方式,您可以在 for 循环中使用 3 种常见类型的串联之一:
- 通过 Concat 函数:
if(allMusic[indexNumb - 1].lyrics['ve'.concat(i)].stamp){
/* Action */
}
- 通过模板文字:
if(allMusic[indexNumb - 1].lyrics[`ve${i}`].stamp){
/* Action */
}
- 或者使用简单的串联 加号:
if(allMusic[indexNumb - 1].lyrics['ve'+i].stamp){
/* Action */
}
我建议你使用第二种方式 2. 模板文字; 因为它的语法更好,使你的代码干净。
评论
lyrics[`ve${i+1}`]
lyrics.length
allMusic = [{ lyrics: { ve: [{ ls: "The club ..." }, { ls: "So the ..." }, { ls: "Me and ..." }] } }]