Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/441.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript中ForLoop到ForEach的转换_Javascript_For Loop_Foreach - Fatal编程技术网

Javascript中ForLoop到ForEach的转换

Javascript中ForLoop到ForEach的转换,javascript,for-loop,foreach,Javascript,For Loop,Foreach,我在练习JavaScript问题。我发现了一个名为“比较三胞胎”的测试。这就是问题所在: a = [1, 2, 3] b = [3, 2, 1] For elements *0*, Bob is awarded a point because a[0] . For the equal elements a[1] and b[1], no points are earned. Finally, for elements 2, a[2] > b[2] so Alice receives

我在练习JavaScript问题。我发现了一个名为“比较三胞胎”的测试。这就是问题所在:

a = [1, 2, 3]
b = [3, 2, 1]
 For elements *0*, Bob is awarded a point because a[0] .
 For the equal elements a[1] and b[1], no points are earned.
 Finally, for elements 2, a[2] > b[2] so Alice receives a point.
 The return array is [1, 1] with Alice's score first and Bob's second.
 
我找到了这样的解决方案:

a=[17,28,30];
设b=[99,16,8];
函数比较程序(a,b){
让记分板=[0,0];
for(设i=0;ib[i])记分板[0]++
如果(a[i]
让a=[17,28,30];
设b=[99,16,8];
函数比较程序(a,b){
让记分板=[0,0];
a、 forEach((元素,i)=>{
如果(元素>b[i])记分板[0]++
else if(元素
这不是你想要的,但让我给你看看:

function compareTriplets(a, b) {
  return [
    (a[0] > b[0]) + (a[1] > b[1]) + (a[2] > b[2]),
    (a[0] < b[0]) + (a[1] < b[1]) + (a[2] < b[2])
  ]
}
函数比较程序(a,b){
返回[
(a[0]>b[0])+(a[1]>b[1])+(a[2]>b[2]),
(a[0]
或者,噪音更小:

function compareTriplets([a, b, c], [d, e, f]) {
  return [
    (a > d) + (b > e) + (c > f),
    (a < d) + (b < e) + (c < f)
  ]
}
函数比较程序([a,b,c],[d,e,f]){
返回[
(a>d)+(b>e)+(c>f),
(a
更简单、更快、更短

我的意思是,它的字面意思是“比较三胞胎”。没有任何动态长度之类的东西;而且循环很短。你可以很容易地做到

a=[17,28,30];
设b=[99,16,8];
函数比较程序([a,b,c],[d,e,f]){
返回[
(a>d)+(b>e)+(c>f),
(a
function compareTriplets([a, b, c], [d, e, f]) {
  return [
    (a > d) + (b > e) + (c > f),
    (a < d) + (b < e) + (c < f)
  ]
}