使用'var undefined'测试未定义是否有任何问题 [英] Is there anything wrong with using 'var undefined' to test for undefined

查看:90
本文介绍了使用'var undefined'测试未定义是否有任何问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此测试未定义是否有任何问题?

Is there anything wrong with this test for undefined?

var undefined;

if(x == undefined){
    //do something
}

或者这个:

function undefined(x){
    return typeof x == 'undefined';
}

if(undefined(x)){
    //do something
}

jsLint不会抛出保留字错误,但代码似乎仍然有用......

jsLint doesn't throws a reserverd word error, but the code still seems to work...

推荐答案

不要重新定义 undefined



其他程序员期望 undefined 总是 undefined ,而不是函数的功能。

Don't redefine undefined.

Other programmers expect undefined to always be undefined, not a function for function's sake.

People通常使用 typeof 运算符来确保在用于测试 undefined 的变量时不会引发引用错误。

People often use typeof operator to ensure a reference error is not thrown when used to test for variables that are undefined.

如果有人对你这么做,你可以使用......

If anyone ever does this to you, you can use...

undefined = void 0;

...将其还原。

这篇关于使用'var undefined'测试未定义是否有任何问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆