如果条件从未满足(即使满足)

时间:2019-03-30 07:40:44

标签: javascript if-statement

我写了if语句,后跟else语句。现在,即使满足条件,它也将转到else语句。

我尝试使用Objects.equal(),但这并不是我真正想要的,因为我使用的是>=符号而不是==符号,这也给了我错误,并且基本上给了我整个程序不起作用。我还尝试将所有条件都设置为默认值,以确保可以满足这些条件,但仍然一无所获。

这是包含if语句的函数。

function evolve() {
            if (coins >= 1000000000 && timesbuyj1 >= 10 && timesbuyj2 >= 10 && timesbuyj3 >= 10) {
                evolutions = evolutions += 1
                var coins = 0
                var timesbuyj1 = 0
                var price01cs = 15
                var timesbuyj2 = 0
                var price1cs = 100
                var timesbuyj3 = 0
                var price8cs = 1100
                var timesbuyj4 = 0
                // a bunch of lines of code that doesn't concern this here //
            } else {
                alert("You don't meet the requirements.")
            }
        } 

当我更改值以满足条件时,我希望所有内容都将重置,更改等。但是它只是告诉我You don't meet the requirements.,并且不会运行应该运行的代码。

1 个答案:

答案 0 :(得分:0)

您正在经历的是变量提升,因为您在if中使用var进行了声明。这意味着,变量不是您想的那样,而是undefined-即使您在函数外部声明了变量。简单示例:

var bar = "foo";

function foo() {
  console.log(bar); // undefined
  if (bar === undefined) { // true, even though you've declared it outside the function; but overriden from var bar = "bar"; inside the if
    alert('hoisting');
    var bar = "bar";
  } else {
    alert('never happens');
  }
}

function baz() {
  console.log(bar);
  if (bar === undefined) { // false, bar was not overriden and still has its value from outside the value
    alert('never happens');
    bar = undefined;
  } else {
    bar = "bar";
    alert(bar);
  }
}

foo();
baz();

要获得所需的行为,请不要使用var两次声明变量,而只需重新分配其值即可

错误:

var coins = 0

右:

coins = 0;

如果您要手动“吊起” foo中的变量,您将编写类似的代码-这就是您的代码现在的解释方式

var bar = "bar";

function foo() {
  var bar;
  console.log(bar);
  if (bar === undefined) { // true, even though you've declared it outside the function; but overriden from var bar = "bar"; inside the if
    alert('hoisting');
    bar = "bar";
  } else {
    alert('never happens');
  }
}

foo()

无论哪种方式,都可以考虑将值实际传递给检查值的函数,而不是依赖全局声明的变量。