P粉2486022982023-08-21 11:40:18
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) // 或者甚至使用数组索引 // (someObject已在问题中定义) resolve("part.0.size", someObject) // 当中间属性未定义时返回null: resolve('properties.that.do.not.exist', {hello:'world'})
P粉2421267862023-08-21 09:38:46
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)