有了对象,我可以在方括号包裹的关键,像这样:有没有简单的方法通过字符串访问数组元素?
// A.js
const category = 'foo'
return { [category] : 'bar' } // { foo: 'bar' }
有没有一种简单的方法做数组元素一样吗?像
// B.js
const category = 'foo'
const items.foo = [1, 2, 3]
const item = 4
return { items: [...items.category, item] } // throws an error
我希望能够得到{项目:1,2,3,4]}在B.js
有没有办法?
它应该是'{项目:[......项目【类别】,项目]}',你应该初始化项目:''const items = {foo:[1,2,3]}'。 –
我想你想'{items:[... items [category],item]}' –
我想访问... items.foo通过... items.'foo',就像我可以访问{foo :'bar'}通过{['foo']:'bar'},以便我不必对foo进行硬编码。 – chachathok