在打开时工作但在重新加载时崩溃

时间:2015-12-17 15:05:41

标签: javascript

所以我尝试在1到3之间创建三个值,每次加载页面时都会有所不同。当我第一次打开页面时,它工作得很好,但每当我尝试重新加载或提交我的表单时,页面都会冻结并且卡住了。非常感谢任何帮助!

function uniqueAnswerId(){
    var rand = (Math.random() * 3.4);
    while (Math.round(rand) == 0) {
        var rand = (Math.random() * 3.4);
    }
    return (Math.round(rand));
}
var answerId1 = uniqueAnswerId();

function uniqueAnswerId2(){
    var rand2 = (Math.random() * 3.4);
    while (answerId1 == Math.round(rand2) || Math.round(rand2) == 0) {
        var rand2 = (Math.random() * 3.4);
    }
    return (Math.round(rand2));
}

var answerId2 = uniqueAnswerId2();

function uniqueAnswerId3(){
    var rand3 = (Math.random() * 3.4);
    while (answerId1 == Math.round(rand3) || answerId2 == Math.round(rand3)){
        while (Math.round(rand3) == 0){
            var rand3 = (Math.random() * 3.4);
        }
    }
    return (Math.round(rand3));
}

var answerId3 = uniqueAnswerId3();

console.log("AnswerIds: " + (answerId1) + ", " + (answerId2) + ", " + (answerId3))

3 个答案:

答案 0 :(得分:1)

你的第3个while循环应该是这样的,另一个" ||"在你的条件而不是一个全新的while循环。

function uniqueAnswerId3(answerId1, answerId2){
    var rand3 = (Math.random() * 3.4);
    while (answerId1 === Math.round(rand3) || answerId2 === Math.round(rand3) || Math.round(rand3)===0){
             rand3 = (Math.random() * 3.4);
    }
    return (Math.round(rand3));
}

答案 1 :(得分:0)

我相信你有一个无限循环。这是修复代码的小提琴。

更改:使用' ==='而不是' =='

函数Hoisting在变量声明之前执行这些函数,这意味着在函数内部引用它们并不起作用。添加了参数以接受所需的参数。

https://jsfiddle.net/80xdmsjL/

function uniqueAnswerId(){
    var rand = (Math.random() * 3.4);
    while (Math.round(rand) === 0) {
        rand = (Math.random() * 3.4);
    }
    return (Math.round(rand));
}

var answerId1 = uniqueAnswerId();

function uniqueAnswerId2(answerId1){
    var rand2 = (Math.random() * 3.4);
    while (answerId1 === Math.round(rand2) || Math.round(rand2) === 0) {
         rand2 = (Math.random() * 3.4);
    }
    return (Math.round(rand2));
}

var answerId2 = uniqueAnswerId2(answerId1);

function uniqueAnswerId3(answerId1, answerId2){
    var rand3 = (Math.random() * 3.4);
    while (answerId1 === Math.round(rand3) || answerId2 === Math.round(rand3)){
        while (Math.round(rand3) === 0){
             rand3 = (Math.random() * 3.4);
        }
    }
    return (Math.round(rand3));
}

var answerId3 = uniqueAnswerId3(answerId1, answerId2);

console.log("AnswerIds: " + (answerId1) + ", " + (answerId2) + ", " + (answerId3))

答案 2 :(得分:0)

看一下代码的这一部分:

while (answerId1 === Math.round(rand3) || answerId2 === Math.round(rand3)){
        while (Math.round(rand3) === 0){
             rand3 = (Math.random() * 3.4);
        }
    }

让我们看看以下值会发生什么:

  • answerId1 = 1
  • answerId1 = 2
  • Math.round(rand3)= 1

在这种情况下,您将拥有:

while (true){
    while(false){
        never_executed();
    }
}

所以它会在外部'while'循环直到无限。

为了避免这种情况你可以简单地做@Nicholas Bakolias所说的,加上'另一个'||“在你的条件而不是一个全新的while循环'