undefined与null的区别
undefined
表示一个变量没有被声明,或者被声明了但没有被赋值null
是一个表示“没有值”的值- Javascript将未赋值的变量默认值设为
undefined
- Javascript从来不会将变量设为
null
。它是用来让程序员表明某个用var
声明的变量时没有值的。 undefined
不是一个有效的JSON,而null
是undefined
的类型(typeof)是undefined
null
的类型(typeof)是object
. 为什么?- 它们都是基本类型
- 他们都是falsy
(
Boolean(undefined) // false
,Boolean(null) // false
) - 你可以这样判断一个变量是否是undefined
typeof variable === "undefined"
- 你可以这样判断一个变量是否是null
variable === null
- 双等号比较时它们相等,但三等号比较时不相等
null == undefined // true
null === undefined // false
MEET THE NEW JSTIPS BOOK
You no longer need 10+ years of experience to get your dream job.
Use the 100 answers in this short book to boost your confidence and skills to ace the interviews at your favorite companies like Twitter, Google and Netflix.
GET THE BOOK NOW
MEET THE NEW JSTIPS BOOK
The book to ace the JavaScript Interview.
A short book with 100 answers designed to boost your knowledge and help you ace the technical interview within a few days.
GET THE BOOK NOW