首页 > 解决方案 > 我的 Javascript 代码使用了 100% 的 CPU 并且无法加载

问题描述

我试图用文字制作一个小游戏。运行代码 Game.start() 函数后,我落后了,没有任何反应。我认为这是 for 循环。请帮助我这是我的代码:

    class unit {
  constructor(health, speed, x, y) {
    this.health = health;
    this.speed = speed;
    this.x = x;
    this.y = y;
  }
  moveTo(xval, yval) {
    this.x = xval;
    this.y = yval;
  }
}

var player = new unit(100, 1, 10, 10);
var unit1 = new unit(50, 1, 1, 12);
var unit2 = new unit(50, 1, 2, 4);
var unit3 = new unit(50, 1, 3, 6);

var i = 0;
var units = 4;
var u = [player, unit1, unit2, unit3];
var k, l, t, r;

function draw(txt) { document.write(txt); };

var Game = {
  width : 20, // Largeur
  height : 20, // Hauteur

  start : function() {
    for(t = 0; t < this.height++; t++) {
    for(k = 0; k < this.width++; k++) {
      for(var x1 = 0; i < units; x1++) {
        if(u[k].x != k) {
          draw('#');
        } else {
          draw('%');
        }
      }
    }
  }
 }
}

标签: javascript

解决方案


因为在函数中的第三个for语句中start,退出条件依赖于在每个循环上i更新x1时,所以你有一个无限循环。


推荐阅读