节点js未定义:1[对象]

vfhzx4xs  于 2021-09-23  发布在  Java
关注(0)|答案(2)|浏览(334)

我正在尝试创建一个discord bot并不断收到此错误。我是一个新手,所以跟随在线教程,让它工作。你能解释一下我为什么会犯这个错误吗。
这是我得到错误的代码。

undefined:1
    [object Object]
request("https://link-to-a-private-json", (e, r, body) => {

    status = JSON.parse(body);
    games = status["content"]["content"];

    cIndex = -1;
    for(i = 0; i < games.length; i++) {
        if(games[i].name === "Game 2") {
            cIndex = i;
            break;
        }
    }

下面是一个json示例

{
  "content": {
    "status": true,
    "content": [
      {
        "name": "Game 1",
        "status": "1",
        "icon": "https://example.com/53MGdfgdfgedNjp.bmp"
      },
      {
        "name": "Game 2",
        "status": "1",
        "icon": "https://example.com/53MGdfgfdedNjp.bmp"
      }
    ]
  }
}
fnvucqvd

fnvucqvd1#

只需更改变量 statuslet status 或者改名。变量 status 是保留关键字,因此需要使用 var , letconst 在你的范围之内。

let body = `{"content": {"status": true, "content": [{"name": "Game 1", "status": "1", "icon": "https://example.com/53MGdfgdfgedNjp.bmp"}, {"name": "Game 2", "status": "1", "icon": "https://example.com/53MGdfgfdedNjp.bmp"}]}}`; 

// defining variable status with let
let status = JSON.parse(body);
games = status["content"]["content"];

cIndex = -1;
for(i = 0; i < games.length; i++) {
  if(games[i].name === "Game 2") {
    cIndex = i;
    break;
  }
}

console.log(cIndex);
des4xlb0

des4xlb02#

使用当前代码要实现的是访问嵌套数组。但这是一个对象,您需要使用不同的方法。
工作演示:https://replit.com/@Kallefromposian/object access#index.js

const json = `{
  "content": {
    "status": true,
    "content": [
      {
        "name": "Game 1",
        "status": "1",
        "icon": "https://example.com/53MGdfgdfgedNjp.bmp"
      },
      {
        "name": "Game 2",
        "status": "1",
        "icon": "https://example.com/53MGdfgfdedNjp.bmp"
      }
    ]
  }
}`;

// Parse json string to object
const {content} = JSON.parse(json);

// Custom found index
let cIndex = -1;

// Loop trough content array
content.content.forEach((item, index) =>{

  // Check do we have string named 'Game 2'
  if(item.name === 'Game 2'){

    // Set index
    cIndex = index;

    // Break loop
    return;
  }

});

相关问题