有了對象,我可以在方括號包裹的關鍵,像這樣:有沒有簡單的方法通過字符串訪問數組元素?
// 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