【问题标题】:Added objects to an array become undefined向数组中添加的对象变得未定义
【发布时间】:2020-12-24 19:03:39
【问题描述】:

所以,我正在为我的 Discord 机器人的命令编写一些代码,该命令将对象添加到存储在 JSON 文件中的对象数组中。这是实现这一目标的代码:

let rawdata = fs.readFileSync('config.json');
let blacklist = JSON.parse(rawdata);

var newWord = {"word": args[3], "count": 0}
blacklist.words.push(newWord);

let data = JSON.stringify(blacklist);
fs.writeFileSync('config.json', data);

它的作用是获取命令中的第 4 个单词 (args[3]) 并将其放入对象 ({"word": args[3], "count": 0}) 中,然后将其添加到 JSON 文件中的对象列表中。这可行,但是当我尝试获取此对象列表时,机器人添加的对象将返回为undefined

这是 JSON 文件:

{"words":[{"string":"test","count":0},{"word":"abc","count":0}]}

列表中的第一个对象{"string":"test","count":0} 我是在创建文件时手动添加的,但是第二个对象{"word":"abc","count":0} 是由机器人添加的。

这是我用来获取对象列表的代码:

var words = ""
for (i = 0; i < blacklist.words.length; i++) {
    words += "- " + blacklist.words[i].string + "\n";
    console.log(blacklist.words[i].string);
}
message.reply("here are the words in your blacklist:\n" + words);

结果如下:

我对 JavaScript 非常陌生,并且一直无法理解它的异步特性,所以我确信我做错了什么。

【问题讨论】:

    标签: javascript json discord.js javascript-objects


    【解决方案1】:

    如果您仔细观察,您会在 JSON 生成的文件中定义两个不同的键:stringword。在这种情况下,您只会看到string 的值,即test。另一个对象没有string 的密钥。

    您可以做的是 1. 更改键以使其匹配或 2. 通过使用内联 if/else 来使用这两个键。

    for (i = 0; i < blacklist.words.length; i++) {
        words += "- " + blacklist.words[i].string + "\n";
        console.log(blacklist.words[i].string || blacklist.words[i].word);
    
    }
    

    【讨论】:

      【解决方案2】:
      for (i = 0; i < blacklist.words.length; i++) {
          words += "- " + blacklist.words[i].string + "\n";
          console.log(blacklist.words[i].string);
      }
      

      此代码要访问黑名单对象的单词数组“字符串”键。 检查您的 JSON 文件第二个元素的键,它不是“字符串”

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-14
        • 2022-12-06
        • 2017-08-31
        • 1970-01-01
        • 2012-08-03
        相关资源
        最近更新 更多