建議如何檢查是否定義了像obj.prop.otherprop.another這樣的對象屬性?JavaScript檢查屬性是否定義
if(obj && obj.prop && obj.prop.otherprop && obj.prop.otherprop.another)
這個效果很好,但足夠難看。
建議如何檢查是否定義了像obj.prop.otherprop.another這樣的對象屬性?JavaScript檢查屬性是否定義
if(obj && obj.prop && obj.prop.otherprop && obj.prop.otherprop.another)
這個效果很好,但足夠難看。
最有效的方法是通過在try {} catch(exception){}塊中檢查obj.prop.otherprop.another。如果所有剩下的都存在,那將是最快的;否則將處理異常。
var a = null;
try {
a = obj.prop.otherprop.another;
} catch(e) {
obj = obj || {};
obj.prop = obj.prop || {};
obj.prop.otherprop = obj.prop.otherprop || {};
obj.prop.otherprop.another = {};
a = obj.prop.otherprop.another ;
}
請不要使用這..這只是我愚蠢的建議這一點。 – jagzviruz 2015-10-13 08:39:49
不是說這是更好,但...
x = null
try {
x = obj.prop.otherprop.another;
} catch() {}
// ...
或可替代...
function resolve(obj, path) {
path = path.split('.');
while (path.length && obj) obj = obj[path.shift()];
return obj;
}
x = resolve(obj, 'prop.otherprop.another');
...但我想實際的答案是,沒有一個BEST-爲此練習。不是我所知道的。
如果你在一個無聊的心情的時候,這會工作:
if ((((obj || {}).prop || {}).anotherprop || {}).another) { ... }
但我不知道是否初始化三個新的對象確實是值得不必重複輸入了路徑。
http://stackoverflow.com/questions/135448/how-do-i-check-to-see-if-an-object-has-a-property-in-javascript – JonH 2013-02-15 17:52:48
@JonH沒有,不是真的... – 2013-02-15 17:53:58