单个for循环如何迭代多个数组?

Abr*_*ado 5 javascript arrays function

在这种情况下,我使用两个并行数组(cost[]scores[]),这两个数组上的数据彼此平行.

这段代码是正确的,因为我从我正在使用的书中复制它.我没有得到的是这个for循环如何为成本数组工作.我得到的是我们将两个数组作为参数传递给函数,但是在for循环中只有scores.length,所以不应该是另一个循环cost.lenght吗?

function getMostCostEffectiveSolution(scores, costs, highScore)  
    var cost = 100;  
    var index;  

    for (var i = 0; i < scores.length; i++) {  
        if (scores[i] == highScore) {  
            if(cost > cost[i]) {
                index = i;  
                cost = cost[i];  
            }
        }
    }
    return index;
}
Run Code Online (Sandbox Code Playgroud)

Pat*_*ans 4

http://en.wikipedia.org/wiki/Parallel_array

在计算中,一组并行数组是表示记录数组的数据结构。它为记录的每个字段保留一个单独的同质数组,每个字段具有相同数量的元素

如果它们确实平行,那么两个数组的长度将相同。

所以scores.length == costs.length。您只需使用一个作为循环条件,并使用相同的索引变量来访问两个数组。

例子

var a = [1,2,3];
var b = [4,5,6];

for(var i=0; i<a.length; i++){
    console.log(a[i] +"  "+ b[i]);
}
Run Code Online (Sandbox Code Playgroud)

输出:

1 4
2 5
3 6
Run Code Online (Sandbox Code Playgroud)

使用 b 的长度

for(var i=0; i<b.length; i++){
    console.log(a[i] +"  "+ b[i]);
}
Run Code Online (Sandbox Code Playgroud)

输出:

1 4
2 5
3 6
Run Code Online (Sandbox Code Playgroud)