Created
January 3, 2014 01:33
-
-
Save brothertao/8230939 to your computer and use it in GitHub Desktop.
安全获取对象属性值
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function getAttrSafe(obj, keyChain, delimiter) { | |
delimiter = delimiter || '.'; | |
if (!keyChain) { throw Error('keyChain should not be a empty value')}; | |
var keys = keyChain.split(delimiter); | |
console.log(keys); | |
try { | |
for (var i = 0; i < keys.length; i++) { | |
obj = obj[keys[i]] | |
if (obj === undefined) { return null;}; | |
}; | |
return obj; | |
} catch (err) { | |
return null; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
测试:
var aa={x:[{},{d:'x1d'}]}; getAttr(aa, 'x.0.d');