跳至正文

JavaScript入门教程笔记(2)-关于null、undefined、true、false

1 null和undefined

1.1 定义

null和undefined都表示“没有”,实际上,将一个变量赋值为null或undefined,语法效果几乎一样。它们的区别是:null是一个表示“空”的对象,转为数值时为0;undefined是一个表示“未定义”的,转为数值时为NaN。

if (null) {} // false
if (undefined) {} // false
null == undefined // true
Number(null) // 0
3 + null // 3
Number(undefined) // NaN
3 + undefined // NaN

1.2 用法

null表示空值,即该处的值现在为空。调用函数时,如果某个参数无需设置任何值,就可以传入null,表示该参数为空。比如,某个函数接受引擎抛出的错误作为参数,如果运行过程中未出错,那么这个参数就会传入null,表示未发生错误。
undefined表示“未定义”,例如:

// 变量声明了,但没有赋值
var i;
i // undefined

// 调用函数时,应该提供的参数没有提供,该参数等于 undefined
function f(x) {
  return x;
}
f() // undefined

// 对象没有赋值的属性
var  o = new Object();
o.p // undefined

// 函数没有返回值时,默认返回 undefined
function f() {}
f() // undefined

2 true和false

除了下面六个值会被转为 false,其它值都被视为true。
- undefined
- null
- false
- 0
- NaN
- “”或'' (空字符串)

注意,空数组和空对象,都是true

if ([]) // true
if ({}) // true

注:本文适用于ES5规范,原始内容来自 JavaScript 教程,有修改。

标签:

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注