我希望在之前添加一个包含2个数组的多数据的数组(Data3):
var Data1 = {2,1,5};
var Data2 = {"a","b","c"};
问题是如何使用这样的循环创建Data3 auto:
var Data3 = [
{
label: Data1[0],
value: Data2[0]
},
{
label: Data1[1],
value: Data2[1]
},
{
label: Data1[2],
value: Data2[2]
}
];
如果data1和data2是动态数组,可以帮我解决那个问题,用for / while自动填充Data3吗?
顺便说一句,对不起我的英语>。<
答案 0 :(得分:1)
您可以使用 forEach()
var Data1 = [2, 1, 5],
Data2 = ["a", "b", "c"],
Data3 = [];
Data1.forEach(function(v, i) {
Data3.push({
label: v,
value: Data2[i]
});
});
document.write(JSON.stringify(Data3));

答案 1 :(得分:0)
这样做:
var Data3 = Data1.map(function(currentValue, index) {
return {label: currentValue, value: Data2[index]};
});
console.log(Data3);
答案 2 :(得分:0)
好的,我假设您的数据是ARRAY,结果也是一个数组:
//this is my proposed solution
function joindata(data1,data2){
if(data1.length == data2.length){
var data3 = []
for(var i=0; i<data1.length ; i++){
data3.push({label: data1[i],
value: data2[i]});
}
return data3;
}
}
//this is an example of how it should be used
var Data1 = [2,1,5];
var Data2 = ["a","b","c"];
var Data3 = joindata(Data1,Data2);
console.log(Data1);
console.log(Data2);
console.log(Data3);
<p> this is here only to print the result </p>
<script src="https://getfirebug.com/firebug-lite-debug.js"></script>