如何判斷 null 與 undefined ?

栏目: JavaScript · 发布时间: 7年前

内容简介:ECMAScript 5ECMAScript 2015

nullundefined 是 ECMAScript 很特別的存在,實務上常常必須判斷 nullundefined ,但如何才是最好的判斷方式呢 ?

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

nullundefined 爲 ECMAScript 5 個 primitive 中之二,最標準的作法就是真的使用 === 判斷 nullundefined

Falsy Value

function foo(x) {
  if (!x) {
    return;
  }
  
  console.log(`x is ${x}`);
}

foo(undefined);
foo(null);
foo(2);
// x is 2

由於 nullundefined 是 Falsy Value,視為 false ,直接使用 ! 即可。

Conclusion

  • 由於 ECMAScript 的 nullundefined 是 Falsy Value,視為 false ,因此有更精簡的寫法,不需要直接判斷 nullundefined

Reference

Dr. Axel Rauschmayer, Speaking JavaScript


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Heuristic Search

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》 这本书的介绍吧!

随机密码生成器
随机密码生成器

多种字符组合密码

html转js在线工具
html转js在线工具

html转js在线工具

HEX CMYK 转换工具
HEX CMYK 转换工具

HEX CMYK 互转工具