动态构建2D数组Javascript

时间:2015-03-06 05:56:52

标签: javascript arrays dynamic

我想动态构建一个二维数组,但我遇到了麻烦。

答案和投票(单个字符串数组)的长度始终相同;

我需要一个这样的数组:

var data = 
        [['Answer', 'Votes'],
        [answers[0],  parseInt(votes[0])],
        [answers[1],  parseInt(votes[1])],
        [answers[2],  parseInt(votes[2])],
          ....
        ];

这不起作用;

var data[];
var arrayLength = answers.length;
for (var i = 0; i < arrayLength; i++) {
    data += [answers[i], votes[i]]; //**Maybe the only line that needs tweaking?
}

4 个答案:

答案 0 :(得分:1)

试试这个:

var data = [];

data[0] = ['answers','votes']

var arrayLength = answers.length;
for (var i = 0; i < arrayLength; i++) {
    data[i+1]= [answers[i], parseInt(votes[i])]; 
}

//check
console.table(data)

答案 1 :(得分:1)

var data = [];
var arrayLength = answers.length;
data[0] = ['Answer', 'Votes'];
for (var i = 1; i < arrayLength; i++) {
    data.push([answers[i], votes[i]]); /*It's not += but .push()*/
}

答案 2 :(得分:0)

试试这个:

var data = [];
var arrayLength = answers.length;
for (var i = 0; i < arrayLength; i++) {
    data.push([answers[i], votes[i]]);
}

答案 3 :(得分:0)

既然您写了answers [i]votes[i],那么您的答案和投票似乎是两个不同的数组。那么为什么需要循环呢。

假设答案和投票是:

var answers = ["A", "B", "C", "D", "E", "F"];
var votes = ["1", "2", "3", "4", "5", "6"];

构建新阵列

var data = ["Answers", "Votes"];

data.Answers=answers;
data.Votes=votes;

console.log(data);