Javascript typeof !== "undefined" vs. != null
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2703102/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
typeof !== "undefined" vs. != null
提问by Derek Thurn
I often see JavaScript code which checks for undefined parameters etc. this way:
我经常看到 JavaScript 代码以这种方式检查未定义的参数等:
if (typeof input !== "undefined") {
// do stuff
}
This seems kind of wasteful, since it involves both a type lookup and a string comparison, not to mention its verbosity. It's needed because undefinedcould be renamed, though.
这看起来有点浪费,因为它涉及类型查找和字符串比较,更不用说它的冗长了。不过,它是必需的,因为undefined可以重命名。
My question is:
How is that code any better than this approach:
我的问题是:
该代码如何比这种方法更好:
if (null != input) {
// do stuff
}
As far as I know, you can't redefine null, so it's not going to break unexpectedly. And, because of the type-coercion of the !=operator, this checks for both undefinedand null... which is often exactly what you want (e.g. for optional function parameters).
据我所知,你不能重新定义null,所以它不会意外中断。而且,由于!=运算符的类型强制,这会检查undefined和null...这通常正是您想要的(例如,对于可选的函数参数)。
Yet this form does not seem widespread, and it even causes JSLint to yell at you for using the evil !=operator.
然而这种形式似乎并不普遍,它甚至会导致 JSLint 因使用邪恶!=运算符而对您大喊大叫。
Why is this considered bad style?
为什么这被认为是不好的风格?
回答by seanmonstar
typeofis safer as it allows the identifier to never have been declared before:
typeof更安全,因为它允许之前从未声明过标识符:
if(typeof neverDeclared === "undefined") // no errors
if(neverDeclared === null) // throws ReferenceError: neverDeclared is not defined
回答by Joey Adams
If the variable is declared (either with the varkeyword, as a function argument, or as a global variable), I think the best way to do it is:
如果声明了变量(使用var关键字、作为函数参数或作为全局变量),我认为最好的方法是:
if (my_variable === undefined)
jQuery does it, so it's good enough for me :-)
jQuery 做到了,所以对我来说已经足够了 :-)
Otherwise, you'll have to use typeofto avoid a ReferenceError.
否则,您将不得不使用typeof来避免ReferenceError.
If you expect undefined to be redefined, you could wrap your code like this:
如果你希望 undefined 被重新定义,你可以像这样包装你的代码:
(function(undefined){
// undefined is now what it's supposed to be
})();
Or obtain it via the voidoperator:
或者通过void运营商获取:
const undefined = void 0;
// also safe
回答by JOKe
good way:
好办法:
if(typeof neverDeclared == "undefined") //no errors
But the best looking way is to check via :
但最好看的方法是通过以下方式检查:
if(typeof neverDeclared === typeof undefined) //also no errors and no strings
回答by Peeter
You shouldn't really worry about undefined being renamed. If someone renames undefined, you will be in a lot more trouble than just a few if checks failing. If you really want to protect your code, wrap it in an IFFE (immediately invoked function expression) like this:
你真的不应该担心 undefined 被重命名。如果有人将 undefined 重命名,如果检查失败,您将遇到更多麻烦。如果您真的想保护您的代码,请将其包装在一个 IFFE(立即调用的函数表达式)中,如下所示:
(function($, Backbone, _, undefined) {
//undefined is undefined here.
})(jQuery, Backbone, _);
If you're working with global variables (which is wrong already) in a browser enviroment, I'd check for undefined like this:
如果您在浏览器环境中使用全局变量(这已经是错误的),我会像这样检查未定义:
if(window.neverDefined === undefined) {
//Code works
}
Since global variables are a part of the window object, you can simply check against undefined instead of casting to a string and comparing strings.
由于全局变量是 window 对象的一部分,您可以简单地检查 undefined 而不是转换为字符串并比较字符串。
On top of that, why are your variables not defined? I've seen a lot of code where they check a variables existence and perform some action based on that. Not once have I seen where this approach has been correct.
最重要的是,为什么你的变量没有定义?我看过很多代码,它们检查变量是否存在并基于此执行一些操作。我一次也没有看到这种方法的正确之处。
回答by Ivo Wetzel
If you are really worried about undefined being redefined, you can protect against this with some helper method like this:
如果你真的担心 undefined 被重新定义,你可以使用一些像这样的辅助方法来防止这种情况:
function is_undefined(value) {
var undefined_check; // instantiate a new variable which gets initialized to the real undefined value
return value === undefined_check;
}
This works because when someone writes undefined = "foo"he only lets the nameundefinedreference to a new value, but he doesn't change the actual value of undefined.
这是有效的,因为当有人写入时,undefined = "foo"他只让名称undefined引用一个新值,但他不会更改undefined.
回答by Claude
You can also use the void operator to obtain an undefined value:
您还可以使用 void 运算符来获取未定义的值:
if (input !== void 0) {
// do stuff
}
(And yes, as noted in another answer, this will throw an error if the variable was not declared, but this case can often be ruled out either by code inspection, or by code refactoring, e.g. using window.input !== void 0for testing global variables or adding var input.)
(是的,正如另一个答案中所述,如果未声明变量,这将引发错误,但这种情况通常可以通过代码检查或代码重构来排除,例如window.input !== void 0用于测试全局变量或添加var input.)
回答by JSpecs
I've actually come across if (typeof input !== 'undefined')in this scenario where it's being used to provide default function parameters:
我实际上遇到过,如果(typeof input !== 'undefined')在这种情况下它被用来提供默认函数参数:
function greet(name, greeting) {
name = (typeof name !== 'undefined') ? name : 'Student';
greeting = (typeof greeting !== 'undefined') ? greeting : 'Welcome';
return `${greeting} ${name}!`;
}
greet(); // Welcome Student!
greet('James'); // Welcome James!
greet('Richard', 'Howdy'); // Howdy Richard!
ES6 provides new ways of introducing default function parameters this way:
ES6 提供了以这种方式引入默认函数参数的新方法:
function greet(name = 'Student', greeting = 'Welcome') {
return `${greeting} ${name}!`;
}
greet(); // Welcome Student!
greet('James'); // Welcome James!
greet('Richard', 'Howdy'); // Howdy Richard!
This is less verbose and cleaner than the first option.
这比第一个选项更简洁、更简洁。
回答by Avinash Maurya
function greet(name, greeting) {
name = (typeof name !== 'undefined') ? name : 'Student';
greeting = (typeof greeting !== 'undefined') ? greeting : 'Welcome';
console.log(greeting,name);
}
greet(); // Welcome Student!
greet('James'); // Welcome James!
greet('Richard', 'Howdy'); // Howdy Richard!
//ES6 provides new ways of introducing default function parameters this way:
function greet2(name = 'Student', greeting = 'Welcome') {
// return '${greeting} ${name}!';
console.log(greeting,name);
}
greet2(); // Welcome Student!
greet2('James'); // Welcome James!
greet2('Richard', 'Howdy'); // Howdy Richard!
回答by Avinash Maurya
var bar = null;
console.log(typeof bar === "object"); //true yes
//because null a datatype of object
var barf = "dff";
console.log(typeof barf.constructor);//function
console.log(Array.isArray(bar));//falsss
console.log((bar !== null) && (bar.constructor === Object)); //false
console.log((bar !== null) && (typeof bar === "object")); // logs false
//because bar!==null, bar is a object
console.log((bar !== null) && ((typeof bar === "object") || (typeof bar === "function"))); //false
console.log(typeof bar === typeof object); //false
console.log(typeof bar2 === typeof undefined); //true
console.log(typeof bar3 === typeof undefinedff); //true
console.log(typeof bar2 == typeof undefined); //true
console.log((bar !== null) && (typeof bar === "object") && (toString.call(bar) !== "[object Array]")); //false
回答by Avinash Maurya
(function(){
var a= b = 3;
var ed = 103;
})();
//console.log(ed); //ed is not defined
console.log("a defined? " + (typeof a !== 'undefined')); //no define
console.log("b defined? " + (typeof b !== 'undefined')); //yes define
console.log(typeof(b)); //number
console.log(typeof(4+7)); //number
console.log(b); //3
console.log(typeof("4"+"7")); //string
var e= "ggg";
console.log(typeof(e)); //string
var ty=typeof(b);
console.log(ty); //number
console.log(typeof false); //boolean
console.log(typeof 1); //number
console.log(typeof 0); //number
console.log(typeof true); //boolean
console.log(typeof Math.tan); //function
console.log(typeof function(){}); //function
if(typeof neverDeclared == "undefined") //no errors
if(typeof neverDeclared === "undefined") //no errors
//if(neverDeclared == null) //showing error
console.log(typeof {a:1}); //object
console.log(typeof null); //object
console.log(typeof JSON); //object
console.log(typeof Math); //object
console.log(typeof /a-z/); //object
console.log(typeof new Date()); //object
console.log(typeof afbc); //undefined
//console.log(typeof new);//error
document.write("<br> * oprator as math ");
var r=14*"4";
document.write(r);
document.write("<br> + oprator as string ");
var r=14+"44";
document.write(r);
document.write("<br> Minus Operator work as mathematic ");
var r=64-"44";
document.write(r);
document.write("<br>");
console.log(typeof(4*"7")); //returns number
console.log(typeof(4+"7")); //returns string
Interview Question in JavaScript

