我想在javascript中使用for循环来组合两个数组的数据

Yas*_*jwa 9 javascript arrays

var stu_names = ['Jhon','Alice','Mik'];
var stu_score = [300,200,400];

for (var i = 0; i < stu_names.length; i++) {
   for(var j = 0; j < stu_score.length; j++) {
       console.log(`Score of ${stu_names[i]} is ${stu_scrore[j]}`);
    }
}
Run Code Online (Sandbox Code Playgroud)

我想得到这样的结果

'Jhon 的分数是 300''Alice 的分数是 200''Mike 的分数是 400'

但不是它,我得到了这个结果

Jhon的
分数是300 Jhon的分数是200 Jhon的
分数是400
Alice的
分数是300 Alice的
分数是200 Alice的
分数是400 Mik的
分数是300 Mik的
分数是200 Mik的分数是400

Nin*_*olz 6

您需要采用相同的索引来获取不同数组的相同值。

var stu_names = ['Jhon', 'Alice', 'Mik'];
var stu_score = [300, 200, 400];

for (var i = 0; i < stu_names.length; i++) {
    console.log(`Score of ${stu_names[i]} is ${stu_score[i]}`);
}
Run Code Online (Sandbox Code Playgroud)


Maj*_*awi 5

您可以使用一个,for loop同时确保两个数组具有相同的长度:

var stu_names = ['Jhon','Alice','Mik'];
var stu_score = [300,200,400];
if(stu_names.length == stu_score.length){
     for(let i = 0; i < stu_names.length; i++)
          console.log(`Score of ${stu_names[i]} is ${stu_score[i]}`);
}
Run Code Online (Sandbox Code Playgroud)