需要帮助来修复我的数学网格迷宫求解器的片段

时间:2016-12-18 23:42:33

标签: javascript arrays for-loop math maze

以下代码背后的想法是测试0到13之间的任何数字+任何其他数字是否等于13.如果有的话,两个数字应保存到不同的数组但是在同一索引上。所以我应该有所有可能的组合来达到两个阵列中的13个。但是当我运行我的代码时,我只得到2个组合,分别是0 + 13和13 + 0。这是代码:



var number1 = [];
var number2 = [];
var index = 0;
var i = 0;
var j = 0;

//Tests if i + j (from the loop) add up to 13
var test = function(i, j) {
  if (i + j === 13) {
    number1[index] = i;
    number2[index] = j;
    index =+ 1;
  }
}

//1st loop generates i from 0 to 13 in 0.5 step.
for (i = 0; i < 13.5; i += 0.5) {

  //same for j, this number should test with i every loop
  for (j = 0; j < 13.5; j += 0.5) {
    test(i, j);
  }
}

//outputs the 2 arrays, the matching numbers should be stored in
for (i = 0; i < number1.length; i++) {
  console.log(number1[i]);
  console.log(number2[i]);
}
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

index =+ 1更改为index += 1

然后index =+ 1index设置为1,不会将其增加1(,如您所愿

请参阅Expressions and operators: Assignment operators MDN