【问题标题】:How can I create dynamic objects with unique variable names inside a loop?如何在循环内创建具有唯一变量名的动态对象?
【发布时间】:2020-10-30 06:52:30
【问题描述】:

我正在尝试以编程方式在 JS 中创建 4 个不同的音频对象。我在这个帖子中看到过类似的帖子:"How do I create dynamic variable names inside a loop?"

但是,变量名的更改利用了循环阶段。在线程内部也有使用 this 关键字的答案,但我不确定如何在循环中以编程方式使用它。

尝试:

var buttonColours = ["red", "blue", "green", "yellow"]
var sounds = [];

for (var i=0; i < buttonColours.length; i++) {
  sounds[i] = new Audio(`sounds/${buttonColours[i]}.mp3`); // Eg. name of audio file - 'blue.mp3'
}

console.log(sounds);

电流输出:

 [audio, audio, audio, audio]

期望的输出(每个存储不同的音频对象,因为它们播放不同的声音)

 [redSound, blueSound, greenSound, yellowSound]

【问题讨论】:

  • 为什么不简单地使用可以命名键的对象?
  • 日志只是说它们是audio 对象。我不确定所述对象的结构,但如果您查找它的路径属性,我敢打赌它是 sounds/red.mp3 等。

标签: javascript arrays for-loop object audio


【解决方案1】:

使用对象代替将音频对象存储在数组中。要使用它们,您可以使用 Object.keys(sounds) 遍历对象的键

var buttonColours = ["red", "blue", "green", "yellow"]
var sounds = {};

for (var i=0; i < buttonColours.length; i++) {
  sounds[buttonColours[i]+"Sound"] = new Audio(`sounds/${buttonColours[i]}.mp3`); // Eg. name of audio file - 'blue.mp3'
}

console.log(sounds);
//{redSound: audio, blueSound: audio, greenSound: audio, yellowSound: audio}

【讨论】:

    猜你喜欢
    • 2011-09-15
    • 2012-01-05
    • 1970-01-01
    • 2015-03-06
    • 1970-01-01
    • 2015-09-10
    • 2021-09-18
    • 2011-01-23
    • 2018-08-20
    相关资源
    最近更新 更多