The use of undefined variables in if-statements

前端 未结 6 1808
别跟我提以往
别跟我提以往 2021-02-05 10:06

This snippet results in a JavaScript runtime error: (foo is not defined)

if (foo) {
    // ...
}

I have to define foo

6条回答
  •  猫巷女王i
    2021-02-05 10:42

    You'll have to define it, to be able to check it for a value. In this case you're checking weather it's true. This variable is obviously not set to anything at all, same as null in C# and Nothing in VB for example.

    If you must, debugging issues or whatever, you could check if the variable is undefined like this:

    if (typeof(variable) == "undefined")
    

提交回复
热议问题