2016-11-22 87 views
-2

所以,我想要一个具有动态属性名称的对象,从数组中检索。这是我到目前为止已经试过:如何使用动态属性名称创建对象

var fruits = {}; 

var props = ['orange', 'apple', 'banana']; 

for (var i = 0; i < props.length; i++) { 
    fruits.props[i] = 'Juice'; 
} 

我的目标应该是这样的:

fruits { orange: 'Juice', apple: 'Juice', banana: 'Juice' }; 

但我得到的错误:

Uncaught TypeError: Cannot set property '0' of undefined(…)

我在做什么错误?

编辑:

不能因为问题的标题是相似的,这个问题本身是也。此问题与695050不同,因为我没有从DOM中检索我的属性名称。我试图循环一个数组,当使用括号符号时,它往往会导致混淆。

+0

'水果[道具[I]] = '果汁';' – somethinghere

回答

2

在您的代码fruits.props[i] = 'Juice';会尝试设置props属性的第0个索引值,其中属性为undefined并导致错误。使用bracket notation使用字符串来分配对象属性。

var fruits = {}; 
 

 
var props = ['orange', 'apple', 'banana']; 
 

 
for (var i = 0; i < props.length; i++) { 
 
    fruits[props[i]] = 'Juice'; 
 
    //----^^^^^^^^^^----- 
 
} 
 

 
console.log(fruits);

2

fruits.props[i] = 'Juice';

需要是:fruits[props[i]] = 'Juice';

由于使用点符号,你不能使用动态属性的名称,但括号表示法,物业有望是一个字符串,该字符串可以是文字或动态获取的值。

+0

Upvoted用于将支架符号的解释。 – Anna

2

您需要括号内的关键字,阅读更多关于property accessors

Property accessors provide access to an object's properties by using the dot notation or the bracket notation.

Syntax

object.property 
object["property"] 

var fruits = {}; 
 

 
var props = ['orange', 'apple', 'banana']; 
 

 
for (var i = 0; i < props.length; i++) { 
 
    fruits[props[i]] = 'Juice'; 
 
    // ^ ^
 
} 
 

 
console.log(fruits);

相关问题