我已经写下了我的第一个JavaScript代码,在网页上进行了一些动态渲染:
var c_names = ["Canada", "USA", "israel"]
var c_ids = [1, 2, 3]
var c_domaain = ["www.canada.com", "www.usa.com", "www.israel.com"]
var data_1 = []
var C_data = [
['Country', 'ids', 'Domain']
]
var x = 1
for (i = 0; i == 3; i++) {
var x = x + 1
data_1.push(c_name[x], c_ids[x], c_domain[x])
for (i = 0; i < c_name.length; i++) {
C_data.push(data_1)
}
}
console.log(C_data)
&#13;
我期待这个输出:
data = [ ['Country', 'ids', 'Domain'],
['USA', 1, 'www.usa.com'],
['Canada', 2, 'www.usa.com'],
['Israel', 3, 'www.usa.com'],
]
答案 0 :(得分:1)
迭代其中一个数组,然后附加相应的项目。
var names = ["Canada", "USA", "israel"]
var ids = [1, 2, 3]
var domains = ["www.canada.com", "www.usa.com", "www.israel.com"]
var data = [
["Country", "ID", "Domain"]
]
names.forEach ((name, idx) => {
data.push ([ name, ids [idx], domains [idx]]);
});
console.log(data)
&#13;
答案 1 :(得分:0)
var c_names = ["Canada","USA","israel" ];
var c_ids = [1,2,3];
var c_domaain = ["www.canada.com","www.usa.com","www.israel.com"];
var data_1 = [];
var C_data = ['Country', 'ids', 'Domain'];
var x = 1;
for(var i = 0; i < c_names.length; i++){
data_1.push(new Array(C_data[i], c_names[i], c_domaain[i]));
};
console.log(data_1);
这是您的代码输出错误:
[ [ "Country", "ids","Domain"],
[ "Canada", 1, "Country"],
[ "USA", 2, "ids" ],
[ "israel", 3, "Domain"]
]
答案 2 :(得分:0)
您可以将数组放在一个数组中,并在尊重索引的同时迭代外部数组和内部数组。
var c_names = ["Canada", "USA", "israel"],
c_ids = [1, 2, 3],
c_domaain = ["www.canada.com", "www.usa.com", "www.israel.com"],
c_data = ['Country', 'ids', 'Domain'],
result = [c_names, c_ids, c_data].reduce(function (r, a) {
a.forEach(function (b, i) {
r[i] = r[i] || [];
r[i].push(b);
});
return r;
}, []);
result.unshift(c_data);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
答案 3 :(得分:0)
var c_names = ["Canada", "USA", "israel"]
var c_ids = [1, 2, 3]
var c_domaain = ["www.canada.com", "www.usa.com", "www.israel.com"]
var C_data = [
['Country', 'ids', 'Domain']
]
var i = -1;
while ( c_names[++i] ) {
C_data.push( [ c_names[i], c_ids[i], c_domaain[i]] );
}
console.log(C_data)