0

私は現在javascriptを学んでおり、このコードにいくつかの問題が見つかりました

var response = '{"status":{"message":{"-1":[111]}}}';
response = jQuery.parseJSON(response);
if ( typeof (response.status.warning[-1]) == "undefined" ) {
    console.log(true);
};

「console.log」部分を無視するのではなく、なぜ彼はエラーをスローするのですか?

dafuq はこの JavaScript です

4

2 に答える 2

2

これをより防御的にコーディングする必要があります。

if (response && (!response.status || !response.status.warning || typeof (response.status.warning[-1]) == "undefined" ) {

response.statusとの存在を確認するresponse.status.warning必要があります。response.status存在しない場合はresponse.status.warning、エラーが発生します

于 2013-03-06T08:04:43.507 に答える
1

この部分を通過することさえできないため:

typeof (response.status.warning[-1]) == "undefined" 

以来response.status.warningですundefined。そのため、エラーがスローされます。


存在するかどうかを確認response.status.warningするには、それが確実でresponseあり.status、そうでない場合にのみundefined:

if(response.status.warning){
    console.log("It exists!");
}
于 2013-03-06T08:02:18.657 に答える