1、null表示"没有对象",即该处不应该有值。
(1) 作为函数的参数,表示该函数的参数不是对象。
(2) 作为对象原型链的终点
(3) 转为数值时为 0 Number null //是数字
2、undefined表示"缺少值",就是此处应该有一个值,但是还没有定义:
(1)变量被声明了,但没有赋值时,就等于undefined。
(2)调用函数时,应该提供的参数没有提供,该参数等于undefined。
(3)对象没有赋值的属性,该属性的值为undefined。
(4)函数没有返回值时,默认返回undefined。
(5)转为数值时为NaN Number undefined //是NaN
var i;
i // undefined
function f(x){console.log(x)}
f() // undefined
var o = new Object();
o.p // undefined
var x = f();
x // undefined
详解举例:
1.1. “作为函数的参数,表示该函数的参数不是对象”
以下举例为 “函数的参数是对象”,并且进行了适当的拓展。
function test(person) {
person.age = 26
person = {
name: 'yyy',
age: 30
}
return person
}
// p1是个对象
const p1 = {
name: 'yck',
age: 25
}
const p2 = test(p1)
console.log(p1) // -> ?
console.log(p2) // -> ?
- p1的结果是yck,26:
test(p1)中p1相当于形参,是一个引用指针,指向内存中的p1,person.age = 26;相当于修改了内存中的age,所以p1 的age为26
- p2的结果是yyy,30:
person = {
name: 'yyy',
age: 30
}
上式相当于新建了一个对象,在内存中新开了一个位置,又通过return 返回,所以p2 就是这个新建的对象
1.2. “ 作为对象原型链的终点”
Object.getPrototypeOf(Object.prototype) //null
1.3. “ 转为数值时为 0”
var a = null;
var res = Number(a);
console.log(res); // 0