This is my solution:
function resolve(path, obj) { return path.split('.').reduce(function(prev, curr) { return prev ? prev[curr] : null }, obj || self) }
Usage example:
resolve("document.body.style.width") // 或者 resolve("style.width", document.body) // 或者甚至使用數(shù)組索引 // (someObject已在問(wèn)題中定義) resolve("part.0.size", someObject) // 當(dāng)中間屬性未定義時(shí)返回null: resolve('properties.that.do.not.exist', {hello:'world'})
There are two ways to access object properties: Dot notation : something.bar and square bracket notation: something['bar'].
The value in the square brackets can be any expression. Therefore, if the property name is stored in a variable, square bracket notation must be used:
var something = { bar: 'foo' }; var foo = 'bar'; // both x = something[foo] and something[foo] = x work as expected console.log(something[foo]); console.log(something.bar)