JQuery while-loop在使用inArray比较优化数组内容时变得无响应

JQuery while-loop becomes unresponsive with inArray comparison to optimise array content

本文关键字:响应 数组 优化 while-loop 比较 inArray JQuery      更新时间:2023-09-26

我有一个函数,它使用一个随机进程来测试数组中的重叠。

像这样:

它获取一个颜色数组,随机选择其中两种并将它们放入一个新数组。然后它测试在这个新的两种颜色的数组new_array中是否有重叠(即我们是否没有两种不同的颜色)。该测试对inArray()的返回索引求和,如果没有重叠则返回0,如果有重叠则返回-1

function test_overlap() {
  window.overlap_output = [];
  var all_colours = ["red", "red", "black", "red", "red", "red", "red", "red", "red"];
  var random_index1 = 1 + Math.floor(Math.random() * 8);
  var random_index2 = 1 + Math.floor(Math.random() * 8);
  var new_array = [all_colours[random_index1], all_colours[random_index2]];
  $.each(new_array, function(i, val) {
    var overlap_test = $.inArray(val, new_array);
    overlap_output.push(overlap_test - i);
  });
  $.each(overlap_output, function() {
    checksum += this;
  });
}

这是我想要的。但是,我现在想将其自动化作为优化,因为它尽可能长时间地运行此函数,直到checksum值为0。换句话说,直到我有一个两种不同颜色的数组。

我想用while在一个新函数中做到这一点:

function optimise_colours() {
  window.checksum = -1;
  while (checksum !== 0){
    test_overlap();
  }
}

在这里,我声明checksumwhile循环中使用,然后在结果不是所需的0时运行它。

然而,如果我运行optimise_colours() -除非它得到一个"完美"数组最初-浏览器得到麻烦,因为它需要太长时间,并返回"无响应的脚本"。

我的问题是这样的:有一种方法来解决我的问题,我在我的代码逻辑犯了一个错误,或者这是不可行的JavaScript/JQuery?

如果有人有类似的问题:我的错误是在我的代码逻辑,因为我怀疑。

在我的while循环中,test_overlap()函数的checksum将随着每次运行而变得更负。我不得不插入一行,在再次求和inArray()索引之前,我将checksum值重置为0:

function test_overlap() {
  window.overlap_output = [];
  var all_colours = ["red", "red", "black", "red", "red", "red", "red", "red", "red"];
  var random_index1 = 1 + Math.floor(Math.random() * 8);
  var random_index2 = 1 + Math.floor(Math.random() * 8);
  var new_array = [all_colours[random_index1], all_colours[random_index2]];
  $.each(new_array, function(i, val) {
    var overlap_test = $.inArray(val, new_array);
    overlap_output.push(overlap_test - i);
  });
#here I need to reset the checksum value to zero
  checksum = 0;
  $.each(overlap_output, function() {
    checksum += this;
  });
}

如果不重置该值,就会发生这种情况:它运行test_overlap()并返回负的checksum,因为存在重叠。校验和值从-1减小到-2。这不是应该满足的条件,所以留在while循环中并再次运行:

现在问题来了:无论第二次运行test_overlap()的结果如何,它最初收到的校验和值是-2,即使这次运行返回的结果是0(即没有重叠),该值也不可能更改为0

在每次checksum计算之前重置此值可修复此问题。

请注意,optimise_colours()checksum的初始值是-1,以便让while循环至少运行一次。

希望这对有类似问题的人有所帮助。