在javascript中包含数组的对象

时间:2015-01-19 05:22:00

标签: javascript node.js

我想构造一个对象,其中一个属性将是一个数组:

var a = 1;
var b = ["a","b"]
var b1 = ["c","d"]
var c = {}

我希望对象c是这样的:

{"prop":1, prop1: ["ac","bd"]}

我尝试这样做:

c.prop = a;
for (var index = 0 ; index < b.length; index++){
    c.prop1[index] = b[index] + b1[index];
}

3 个答案:

答案 0 :(得分:2)

您可以将对象中的属性prop1初始化为空数组[],然后使用push方法向其中添加适当的对象。代码:

var a = 1;
var b = ["a","b"]
var b1 = ["c","d"]
var c = {}
c.prop = a;
c.prop1 = []; // initialization
for (var index = 0 ; index < b.length; index++){
    c.prop1.push(b[index] + b1[index]); // pushing computed values
}

答案 1 :(得分:1)

我认为您需要首先定义数组prop1,然后才能开始为其添加值;

c.prop = a;
c.prop1 = [];       // declare prop1 to be an empty array
for (var index = 0 ; index < b.length; index++){
    c.prop1[index] = b[index] + b1[index];
}

答案 2 :(得分:1)

var associativeArray = {};
associativeArray["one"] = [];
associativeArray["two"] = [];
associativeArray["three"] = [];

如果您来自OO语言,那么您应该查看this