我正在尝试使用动态名称访问对象的属性。这可能吗?
const something = { bar: "Foobar!" };
const foo = 'bar';
something.foo; // The idea is to access something.bar, getting "Foobar!"
最佳答案
有two ways to access properties对象:
- 点符号:
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)
关于javascript - 使用变量动态访问对象属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4244896/