我从服务器收到此JSON,我需要检查它是否包含密钥read.nores
如果我这样做
if (data[0]["read.nores"]) {
return;
}
它会崩溃,因为它不包含该密钥。
如何在没有try / catch方法的情况下检查密钥是否存在,例如.has(" read.nores")?
答案 0 :(得分:1)
它不会崩溃。
如果检查对象的任何属性,并且未在对象中定义它,则默认为undefined
。所以你的if条件会完美运作。
答案 1 :(得分:1)
安全地读取未定义的密钥会产生(function (global) {
System.config({
paths: {
// paths serve as alias
'npm:': 'node_modules/'
},
// map tells the System loader where to look for things
map: {
// our app is within the app folder
app: 'app',
// angular bundles
'@angular/core': 'npm:@angular/core/bundles/core.umd.js',
'@angular/common': 'npm:@angular/common/bundles/common.umd.js',
'@angular/compiler': 'npm:@angular/compiler/bundles/compiler.umd.js',
'@angular/platform-browser': 'npm:@angular/platform-browser/bundles/platform-browser.umd.js',
'@angular/platform-browser-dynamic': 'npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js',
'@angular/http': 'npm:@angular/http/bundles/http.umd.js',
'@angular/router': 'npm:@angular/router/bundles/router.umd.js',
'@angular/router/upgrade': 'npm:@angular/router/bundles/router-upgrade.umd.js',
'@angular/forms': 'npm:@angular/forms/bundles/forms.umd.js',
'@angular/upgrade': 'npm:@angular/upgrade/bundles/upgrade.umd.js',
'@angular/upgrade/static': 'npm:@angular/upgrade/bundles/upgrade-static.umd.js',
// other libraries
'rxjs': 'npm:rxjs',
'angular-in-memory-web-api': 'npm:angular-in-memory-web-api/bundles/in-memory-web-api.umd.js',
'ng2-ckeditor': 'npm:ng2-ckeditor',
},
// packages tells the System loader how to load when no filename and/or no extension
packages: {
app: {
main: './main.js',
defaultExtension: 'js'
},
'ng2-ckeditor': {
defaultExtension: 'js'
},
rxjs: {
defaultExtension: 'js'
}
}
map: {
"ng2-ckeditor": "node_modules/ng2-ckeditor/lib/ckeditor.component.js"
}
});
})(this);
,但是从undefined
读取密钥会抛出,因此问题将明确表示undefined
不存在,而不是{ {1}}不存在。
要检查,请将其更改为:
data[0]