javascript 在javascript中向数组或对象添加多个值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19119214/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
adding multiple values to an array or object in javascript
提问by r.r
i like to have array or object like:
我喜欢有数组或对象,如:
[0]
text:"first"
id: 1
[1]
text:"second"
id: 2
[2]
text:"third"
id: 3
getting myself:
让自己:
1: first
2: 1
3: second
4: 2
5: third
6: 3
here is my javascriptwith implementation for the arrayat the moment:
这是我目前实现数组的javascript:
var numberOfQuestions = questionaireResult.numberOfQuestions;
var i;
var j;
var result = [];
for (i = 0; i < numberOfQuestions; i++) {
debugger;
var question = questionaireResult.questions[i].text;
var questionID = questionaireResult.questions[i].id;
for (j = 0; j < questionaireResult.questions[i].answers.length; j++) {
var text = questionaireResult.questions[i].answers[j].text;
var id = questionaireResult.questions[i].answers[j].id;
result.push(text, id);
}
}
please help to get a structured array or object
请帮助获取结构化数组或对象
回答by Andy
Push an object containing your data to the array instead:
将包含数据的对象推送到数组:
result.push({text: text, id: id});
回答by leaf
Assuming that you want to store all answers into a single array, you could use concat
to get the expected result and reduce the amount of code at the same time :
假设您想将所有答案存储到单个数组中,您可以使用concat
来获得预期结果并同时减少代码量:
var questions = questionaireResult.questions,
result = [],
l = questions.length,
i = 0;
for (; i < l; i++) {
result = result.concat(
questions[i].answers
);
}
Here is how concat
works (mdn doc) :
这是concat
工作原理(mdn doc):
var a = [1, 2, 3],
b = [4, 5, 6];
a.concat(b); // [1, 2, 3, 4, 5, 6]