如何判斷 null 與 undefined ?
栏目: JavaScript · 发布时间: 7年前
内容简介:ECMAScript 5ECMAScript 2015
null
與 undefined
是 ECMAScript 很特別的存在,實務上常常必須判斷 null
與 undefined
,但如何才是最好的判斷方式呢 ?
Version
ECMAScript 5
ECMAScript 2015
標準做法
function foo(x) {
if (x === null || x === undefined) {
return;
}
console.log(`x is ${x}`);
}
foo(undefined);
foo(null);
foo(2);
// x is 2
null
與 undefined
爲 ECMAScript 5 個 primitive 中之二,最標準的作法就是真的使用 ===
判斷 null
與 undefined
。
Falsy Value
function foo(x) {
if (!x) {
return;
}
console.log(`x is ${x}`);
}
foo(undefined);
foo(null);
foo(2);
// x is 2
由於 null
與 undefined
是 Falsy Value,視為 false
,直接使用 !
即可。
Conclusion
-
由於 ECMAScript 的
null與undefined是 Falsy Value,視為false,因此有更精簡的寫法,不需要直接判斷null與undefined
Reference
Dr. Axel Rauschmayer, Speaking JavaScript
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网
猜你喜欢:本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Heuristic Search
Stefan Edelkamp、Stefan Schrodl / Morgan Kaufmann / 2011-7-15 / USD 89.95
Search has been vital to artificial intelligence from the very beginning as a core technique in problem solving. The authors present a thorough overview of heuristic search with a balance of discussio......一起来看看 《Heuristic Search》 这本书的介绍吧!