JavaScript 中的动态变量名称 [duplicate]

Dynamic Variable Name In JavaScript [duplicate]

提问人:Adam Hunter 提问时间:11/14/2023 最后编辑:blackgreenAdam Hunter 更新时间:11/14/2023 访问量:82

问:

我正在尝试做一个循环函数,它将从数组中获取歌词诗句。我确实有一个工作函数,但没有动态变量。我想要的只是某种程度上的动态 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",
      },
     },
    },
]
JavaScript 数组函数 变量

评论

1赞 pilchard 11/14/2023
您需要创建一个字符串键lyrics[`ve${i+1}`]
3赞 JoSSte 11/14/2023
结构是固定的,还是可以重写它以将歌词放在数组中?
0赞 Jared Smith 11/14/2023
另请注意,您的代码正在尝试读取,歌词是一个对象,没有长度。lyrics.length
1赞 Pointy 11/14/2023
如果“lyrics”属性是数组而不是对象,那就简单多了。每当你发现自己有(基本上)数字键时,就像你的例子一样,不使用普通的旧数组是很奇怪的。
1赞 Wyck 11/14/2023
有些日子你修复代码,有些日子你修复数据。今天可能是后者。allMusic = [{ lyrics: { ve: [{ ls: "The club ..." }, { ls: "So the ..." }, { ls: "Me and ..." }] } }]

答:

2赞 Omar Khaled 11/14/2023 #1

通过这种方式,您可以在 for 循环中使用 3 种常见类型的串联之一:

  1. 通过 Concat 函数:

     if(allMusic[indexNumb - 1].lyrics['ve'.concat(i)].stamp){
      /* Action */
     }
  1. 通过模板文字:

     if(allMusic[indexNumb - 1].lyrics[`ve${i}`].stamp){
      /* Action */
     }
  1. 或者使用简单的串联 加号:

    if(allMusic[indexNumb - 1].lyrics['ve'+i].stamp){
     /* Action */
    }

我建议你使用第二种方式 2. 模板文字; 因为它的语法更好,使你的代码干净。