如何检查变量是否已设置并存在于 javascript?

How to check variable is set and exists from javascript?

我得到以下 json 数据:

{
  "ID": [
    "The i d field is required."
  ],
  "terms_condition": [
    "The terms condition field is required."
  ]
}

并存储在变量中:

var DataJson = data.responseText;
var Json = JSON.parse(DataJson);

var IdError = Json.ID[0];
var TermsConditionError = Json.terms_condition[0];

ID 不是 exists

时,我收到此错误 Uncaught TypeError: Cannot read property '0' of undefined

我已尝试使用此示例来防止错误处理。

if (typeof Json.ID[0] !== 'undefined') {
    alert('validation message found');
} else {
    alert('validation message not found');
}

但这不起作用不知道我做错了什么?

谢谢。

要检查是否定义了变量或字段,您可以将其与 undefined

进行比较
if ((Json !== undefined) && (Json.ID !== undefined) && (Json.ID[0] !== undefined)) {
    alert('validation message found');
} else {
    alert('validation message not found');
}

我没有发现您的代码有任何问题。请参阅下面的代码段。

var Json = JSON.parse('{"ID": ["The i d field is required."], "terms_condition": ["The terms condition field is required."]}');

var IdError = Json.ID[0];
var TermsConditionError = Json.terms_condition[0];

document.writeln(IdError + '<br>');
document.writeln(TermsConditionError + '<br>');
document.writeln('==================<br>');

function isDefined(Json) {
  return (Json !== undefined) && (Json.ID !== undefined) && (Json.ID[0] !== undefined);
}
  
var inputData = [
  undefined,
  {},
  {ID: ''},
  {ID: ['value']}
];

inputData.forEach(function(inputDaten) {
  document.writeln(JSON.stringify(inputDaten) + ': ' + isDefined(inputDaten) + '<br>');
});

可能问题出在 data.responseText

试试这个。

 if (Json !=undefined && typeof Json.ID[0] != undefined ) {
        alert('validation message found');
    } else {
        alert('validation message not found');
    }

TypeError: Cannot read property '0' of undefined

当主要 json 对象为空或未定义时会发生此错误。当 json 对象中没有数据时会发生这种情况。