我正在解析 JSON 并尝试访问它的一个字段,它是一个数组。
const myObj: MyObj = JSON.parse(myJson);
console.log(myObj.myArray); //SyntaxError: Unexpected end of JSON input
console.log(myObj.myArray == 'undefined'); //SyntaxError: Unexpected end of JSON input
console.log(myObj.myArray.length); //TypeError: Cannot read property 'length' of undefined
console.log(myObj.myArray !== null); //true
我可以毫无问题地遍历我的数组并对数据执行我需要的操作。但我需要检查以确保 myArray
字段在迭代时有效。当我尝试执行此操作时,出现如上所示的错误。
我非常非常困惑。谁能向我解释一下发生了什么事以及如何解决它?
最佳答案
使用 in
时要小心,因为它会搜索整个原型(prototype)链。
const myJson = '{"a": 2}';
const myObj = JSON.parse(myJson);
console.log('constructor' in myObj); // true (BAD)
相反,尝试使用 .hasOwnProperty()
,如下所示:
const myJson = '{"a": 2}';
const myObj = JSON.parse(myJson);
console.log(myObj.hasOwnProperty("a")); // true
console.log(myObj.hasOwnProperty("constructor")); // false
关于javascript - 如何检查我的 JSON 字段是否已定义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60141364/