Heim > Fragen und Antworten > Hauptteil
Ich versuche, mithilfe dynamischer Namen auf die Eigenschaften eines Objekts zuzugreifen. Ist es möglich?
const something = { bar: "Foobar!" }; const foo = 'bar'; something.foo; // The idea is to access something.bar, getting "Foobar!"
P粉0989790482023-10-11 12:39:43
这是我的解决方案:
function resolve(path, obj) { return path.split('.').reduce(function(prev, curr) { return prev ? prev[curr] : null }, obj || self) }
使用示例:
resolve("document.body.style.width") // or resolve("style.width", document.body) // or even use array indexes // (someObject has been defined in the question) resolve("part.0.size", someObject) // returns null when intermediate properties are not defined: resolve('properties.that.do.not.exist', {hello:'world'})
P粉7558637502023-10-11 12:17:15
有两种访问属性的方法 对象:
something.bar
something['bar']
括号内的值可以是任意表达式。因此,如果属性名称存储在变量中,则必须使用括号表示法:
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)