2014-04-09 41 views
2

因爲nullundefined不是JavaScript中的對象,我猜它可能是全局幫助函數?Rails對所有對象都有一個「try」方法。有沒有辦法在JavaScript中做類似的事情?

用法示例可能是這樣的:

var a = { b: { c: { d: 'hello world!' } } }; 
tryPath(a, 'b', 'c', 'd'); // returns 'hello world!' 
tryPath(a, 'x', 'c', 'd'); // returns undefined 
+0

po可能的重複[可能忽略無法讀取屬性'0'的未定義?](http://stackoverflow.com/questions/22145087/possible-to-ignore-cannot-read-property-0-of-undefined) –

回答

0
var tryPath = function tryPath() { 
    if (arguments.length < 2) { 
     return undefined; // Not valid 
    } else { 
     var object = arguments[0]; 
     for (var i = 1; i < arguments.length; i++) { 
      if (object !== null && typeof object === 'object') { 
       object = object[arguments[i]]; 
      } else { 
       return undefined; 
      } 
     } 
     return object; 
    } 
}; 
2

你甚至可以Array.prototype.reduce縮短,這樣

function tryPath(object) { 
    var path = Array.prototype.slice.call(arguments, 1); 
    if (!path.length) return undefined; 
    return path.reduce(function(result, current) { 
     return result === undefined ? result : result[current]; 
    }, object); 
} 

var a = { b: { c: { d: 'hello world!' } } }; 
console.assert(tryPath(a, 'b', 'c', 'd') === 'hello world!'); 
console.assert(tryPath(a, 'x', 'c', 'd') === undefined); 
console.assert(tryPath(a) === undefined); 
+0

偉大,除了是使用嵌套函數,所以它可能會更慢? –

1

你可以做一些非常簡單的無輔助函數:

var a = { b: { c: { d: 'hello world!' } } }; 
a && a.b && a.b.c && a.b.c.d; // returns 'hello world!' 
a && a.x && a.x.c && a.x.c.d; // returns undefined 
相關問題