【问题标题】:Bug in JavaScript Code? For loop vs Foreach loop [duplicate]JavaScript 代码中的错误? For循环与Foreach循环[重复]
【发布时间】:2020-05-13 06:41:05
【问题描述】:

我用两种不同的方式编写了相同的代码,它们之间的唯一区别是一种使用 for 循环,而另一种使用 foreach环形。但是,它们似乎给出了不同的结果。

结果的图片可以在底部找到。

这段代码检查蓝色矩形是否与紫色灰色矩形相交,如果相交,则返回false。 每次创建新的蓝色矩形时都会运行这段代码

这样做的目的是确保没有蓝色矩形位于灰色区域所界定的区域之外或绿色区域内

const USE_FOR = true;

// wall.type: string value, possible values: 'bound', 'base', 'random'
// CONFIG.wall.bound_type: 'gray'
// CONFIG.wall.base_type: 'base'

// 'bound' type: gray rectangles
// 'base' type: purple rectangles
// 'random' type: blue rectangles
if (USE_FOR) {
    for (let i = 0; i < walls.length; i++) {
        let wall = walls[i];

        if (wall.type == CONFIG.wall.base_type || wall.type == CONFIG.wall.bound_type) {
            if (isCollision(wall.getArea(), area)) {
                return false;
            }
        }
    }
} else {
    walls.forEach((wall) => {
        if (wall.type == CONFIG.wall.base_type || wall.type == CONFIG.wall.bound_type) {
            if (isCollision(wall.getArea(), area)) {
                return false;
            }
        }
    });
}

return true;

Result from using the for loop

Result from using the foreach loop

【问题讨论】:

  • return in for 循环退出外部函数。 foreach 循环中的 return 只退出内部的 anon 函数(什么都不做)

标签: javascript


【解决方案1】:

当您的谓词匹配时,您可以使用Array.prototype.somereturn,而不是使用Array.prototype.forEach

const array = [1, 2, 3, 4, 5];

function demoFor(array, predicate, useFor = true) {
  if (useFor) {
    for (let i = 0; i < array.length; i++) {
      if (predicate(array[i])) return false;
      else console.log(array[i]);
    }
  } else {
    return !array.some((e) => {
      if (predicate(e)) return true;
      else console.log(e);
    });
  }
}
const predicate = (e) => e === 3;
console.log("Using for loop");
demoFor(array, predicate, true);
console.log("Using some");
demoFor(array, predicate, false);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-08-10
    • 1970-01-01
    • 1970-01-01
    • 2020-01-03
    • 2012-03-02
    • 2014-03-23
    • 2018-12-11
    相关资源
    最近更新 更多