如何使用数组值向对象添加键?

时间:2015-06-17 16:29:21

标签: javascript arrays

我被要求向对象(名为myObject)添加一个键(名为interest)。密钥必须具有数组值。在这里我发布代码。但它不起作用。

var interests=[];
var myObject = {
  name: 'Eduardo',
  type: 'Most excellent',

  // Add your code here!
  interests:'reading',
  interests:'singing'
};

1 个答案:

答案 0 :(得分:0)

var interests = [];
var myObject = {
    name: 'Eduardo',
    type: 'Most excellent',
    interests: ['reading', 'singing']
};

或者如果您尝试使用已创建的数组:

var interests = ['reading', 'singing'];
var myObject = {
    name: 'Eduardo',
    type: 'Most excellent',
    interests: interests
};

或者在创建myObject后添加它:

var myObject = {
    name: 'Eduardo',
    type: 'Most excellent'
};
myObject.interests = interests;