JavaScript无限循环,而代数减为负? [英] JavaScript infinity loop while generation numbers with minus?
问题描述
我有用于解决数学问题(简单的数学问题)的JavaScript代码。一切都是随机的。
使用plus(+),一切正常。
ex
I have JavaScript code that is used to make math problems(simple math questions). Everything is randomized. With plus(+) everything works fine. e.x.
1 + 3
2 + 4
8 + 9
该函数检查第一个负数参数的数字大于第二个(执行1-2 false; 2-1代码执行)无限循环。我对解释的理解不好,希望当您看到代码时会得到它。
When the function that check if the first number for minus parameter is greater that the second(1-2 false;2-1 code executes) an infinity loop happens. I'm not good with the explanations hope will will get it when you see the code.
输出的结构是:
1-10(随机)中带正号的数字
the numbers from 1-10(random) with plus
1-10(随机)中带负号的数字
the numbers from 1-10(random) with minus
1-100(随机)中的数字加上
the numbers from 1-100(random) with plus
1-10(随机)中的数字减去
the numbers from 1-10(random) with minus
<html>
<p id='plus10'></p>
<p id='minus10'></p>
<p id='plus100'></p>
<p id='minus100'></p>
<script>
arr2 = [];
var lastArr2 = [];
var num1,num2;
//FIRST ARRAY
while(lastArr2.length<121){
arr2.push('<br>'+Math.round(Math.random() * 10)+'+'+Math.round(Math.random() * 10)+'=');
lastArr2=removeDuplicates(arr2);
}
document.getElementById('plus10').innerHTML=(lastArr2.join(' '));
//SECOND ARRAY
arr1 = [];
var lastArr1 = [];
while (lastArr1.length < 121) {
arr1.push('<br>' + Math.round(Math.random() * 100) + '+' + Math.round(Math.random() * 100) + '=');
lastArr1 = removeDuplicates(arr1);
}
document.getElementById('plus100').innerHTML = (lastArr1.join(' '));
//THIRD ARRAY
arr3 = [];
var lastArr3 = [];
while (lastArr3.length < 121) {
gen();
}
function gen(){
//minus function
num1=Math.round(Math.random()*10);
num2=Math.round(Math.random()*10);
if(num1<num2){
gen();
}else{
lastArr3 = removeDuplicates(arr3);
arr1.push(num1+'-'+num2+'=');
}
}
document.getElementById('minus10').innerHTML = (lastArr3.join(' '));
function removeDuplicates(arr){
let unique_array = []
for(let i = 0;i < arr.length; i++){
if(unique_array.indexOf(arr[i]) == -1){
unique_array.push(arr[i])
}
}
return unique_array
}
</script>
</html>
编辑:
我错了
I was wrong about
arr1.push(num1+'-'+num2+'=');
应该是
arr3.push(num1+'-'+num2+'=');
但这不能解决无限循环
推荐答案
在您的 gen()
函数内部, arr1.push( )
可能应该是 arr3.push()
,否则循环条件将永远不会改变,并且将保持无限循环。
Inside your gen()
function, arr1.push()
should probably be arr3.push()
, otherwise the looping condition will never change and it will stay in infinite loop.
这篇关于JavaScript无限循环,而代数减为负?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!