【问题标题】:How can I access user-selected variable from a JSON file? (Node.js)如何从 JSON 文件访问用户选择的变量? (Node.js)
【发布时间】:2018-11-24 19:37:04
【问题描述】:

这是交易:我正在尝试从 JSON 文件中的变量中获取数据,该变量的名称使用不同的变量。基本上,我想通过将“M83”替换为“Bands”来访问 MusicJSON.Bands.M83.length,否则,我必须将 JSON 文件中的每个变量都添加到我的代码中,这违背了我的目的。这是我的代码:

    for(i = 0; i < MusicJSON.Bands.Names.length; i++) {
            var Band = MusicJSON.Bands.Names[i]
            NextMessage += "\n " + Band + MusicJSON.Bands.length + "  songs"; // Right here
        }
        NextMessage += "**";
        message.channel.send(`Here's a list of bands available on this server: \n ${NextMessage}`)

【问题讨论】:

    标签: json node.js discord.js


    【解决方案1】:

    我正在努力实现您想要做的事情。如果你的MusicJSON.Bands 是这样的:

    {
      Names: ["1", "2", "3", "M83"],
      1: ["song1", "song2", "song3"],
      2: ["song1", "song2", "song3"],
      3: ["song1", "song2", "song3"],
      M83: ["Midnight City", "Wait", "Outro"]
    }
    

    如果你想得到每个波段的长度,试试这个:

    var next = "";
    for (let name of MusicJSON.Bands.Names) { //automatically loop through the array
      let number = MusicJSON.Bands[name].length; //access the object like MusicJSON.Bands["M83"]
      next += `\n${name}: ${number} songs` //add the text
    }
    next += "**";
    message.channel.send(`Here's a list of bands available on this server:\n${next}`);
    

    另外,请记住,如果名称是对象中的键,则不需要存储名称,因为您可以像这样循环键:

    MusicJSON.Bands = {
      M83: ["Midnight City", "Wait", "Outro"],
      "System Of A Down": ["Toxicity", "Chic 'N' Stu", "Chop Suey"]
    }
    
    var names = Object.keys(MusicJSON.Bands).sort(), //create and array with the keys and sort it
      next = "";
    
    for (let band of names) {
      next += `\n${band}: ${MusicJSON.Bands[band].length} songs`;
    }
    next += "**";
    message.channel.send(`Here's a list of bands available on this server:\n${next}`);
    

    我希望这是你想做的事情

    【讨论】:

      猜你喜欢
      • 2015-07-22
      • 2021-10-07
      • 1970-01-01
      • 1970-01-01
      • 2019-10-06
      • 2020-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-08
      相关资源
      最近更新 更多