2017-12-18 101 views
1

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

// 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

有沒有辦法?

+0

它應該是'{項目:[......項目【類別】,項目]}',你應該初始化項目:''const items = {foo:[1,2,3]}'。 –

+1

我想你想'{items:[... items [category],item]}' –

+0

我想訪問... items.foo通過... items.'foo',就像我可以訪問{foo :'bar'}通過{['foo']:'bar'},以便我不必對foo進行硬編碼。 – chachathok

回答

2

兩個點號和方括號property accessors

如果使用點符號,屬性必須是實際的屬性名稱:

words=new Object; 
 
    words.greeting='hello'; 
 
    console.log(words.greeting);  //hello 
 
    console.log(words['greeting']); //hello 
 
    console.log(words[greeting]); //error

在第三個例子,greeting被視爲一個變量,而不是作爲一個字符串字面,並且因爲greeting尚未定義爲變量,所以JavaScript解釋器會引發錯誤。

如果我們定義greeting作爲一個變量:

var greeting = 'greeting'; 

第三示例工作:

words=new Object; 
 
    words.greeting='hello'; 
 
    var greeting='greeting'; 
 
    console.log(words[greeting]);

因此,你需要用方括號屬性訪問:

[...items[category],item] 
0

您可以使用相同的語法:

const category = 'foo' 
 
const items = {foo: [1, 2, 3]} 
 
const item = 4 
 
    
 
console.log({ items: [...items[category], item] })

0

如果要使用另一個變量來訪問foo屬性,你可以用方括號符號,就像這樣:

const category = 'foo' 
const items = { 
    foo: [1, 2, 3] 
} 

const item = 4 

console.log({ items: [...items[category], item] }); 
相關問題