2017-12-18 105 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] }); 
相关问题