在if语句中使用未定义的变量

在if语句中使用未定义的变量

本文介绍了在if语句中使用未定义的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此代码段导致JavaScript运行时错误:( foo 未定义)

  if(foo){
// ...
}

我必须首先定义 foo ,如下所示:

  var foo = foo || null //或undefined,0等。

......只有这样才能做到:

  if(foo){
// ... ...
}

为什么?






更新:





你可以做的有趣的事情typeof()在一个未定义的变量上。我会接受的回答,因为我认为这是最优雅的解决方案。

解决方案

您必须定义它,才能检查它的值。在这种情况下,你正在检查天气是否属实。这个变量显然没有设置为任何东西,例如C#中的null和VB中的Nothing。



如果必须,调试问题或其他什么,你可以检查如果变量未定义如下:

  if(typeof(variable)==undefined)


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

if (foo) {
    // ...
}

I have to define foo first, like so:

var foo = foo || null // or undefined, 0, etc.

... And only then can I do:

if (foo) {
    // ...
}

Why is that?


Update:

This was somewhat of a brainfart on my side of things: 'fcourse you can't access a variable which is not allocated.

Fun stuff that you can do a typeof() on an undefined variable thou. I'm gonna accept miccet's answer since I think it's the most elegant solution.

解决方案

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")

这篇关于在if语句中使用未定义的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 18:42