如何在JavaScript中处理未定义的JSON数据?

时间:2016-04-15 17:40:12

标签: javascript json

以下是代码:

if (data.result.parameters.q === undefined ) {
    colsole.log('undefined')
}
//I also tried
if (data.result.parameters.q === null) {
    //   colsole.log('undefined')
// }

尝试过使用null和undefined但没有效果。

1 个答案:

答案 0 :(得分:1)

a === undefined不一定会检查undefined,因为您可以设置var undefined = {}

使用voidtypeof运算符(不需要严格相等===):

if(data.result.parameters.q == void(0) || typeof data.result.parameters.q == 'undefined')
    console.log('data.result.parameters.q is undefined');

您的数据实际上看起来如何?您确定datadata.resultdata.result.parameters已设置好吗?有很多方法可以检查,例如hasOwnProperty或一般truthiness

if(data.hasOwnProperty('result') && data.result && data.result.hasOwnProperty('parameters'))
    // now we can check if there is q in data.result.parameters

另请注意,您的代码中存在拼写错误:它是console,而不是colsole