导航
undefined
、 null
string
、 boolean
、 number
symbol
(es6)、bigint
(es10)object
两种类型的区别是:存储位置不同;
undefined
string
、 boolean
、 number
symbol
、bigint
function
object
(包含 array、null)"undefined"
console.log(typeof [] === 'object'); // true
console.log(typeof null === 'object'); // true
console.log(typeof(undefined)); // undefined
console.log(typeof(NaN)); // number
console.log( typeof(1 - "1") ) // number
console.log( typeof("1" - "1") ) // number
console.log(a) // Uncaught ReferenceError: a is not defined.
console.log( typeof(a) ) // undefined
console.log( typeof(typeof(a)) ) // string; hint: typeof() 返回的是字符串
function Car(make, model, year) {
this.make = make;
this.model = model;
}
var auto = new Car('Honda', 'Accord');
console.log(auto instanceof Car);
// expected output: true
console.log(auto instanceof Object);
// expected output: true
window.undefined
null == undefined
console.log(window.undefined);
window.undefined = 1; // 不可修改
console.log(window.undefined);
delete window.undefined; // 不可删除
console.log(window.undefined);
for (var k in window) { // 不可枚举
if (k === undefined) {
console.log(k);
}
}
Object.defineProperty(window, 'undefined', {
enumerable: true,
writable: true,
configurable: true
});
function test() {
// undefined 不是 JS 的保留字和关键字
var undefined = 1;
console.log(undefined);
console.log(window.undefined === void(100));
console.log(undefined === void(12));
}
test();
拓展
if(xx == null)
来判断变量 xx 是否为 undefined
和 null
,这样可以更加简洁。(在目前最新的语法中 ??
就是只针对 undefined
和 null
做判断处理的,如 let a = xx ?? 123
)null
,这样可以避免内存泄漏let a = undefined;
let x = a ?? 123;
console.log(x); // 123
let a = null;
let x = a ?? 123;
console.log(x); // 123
// 非 undefined 或 null,则不处理
let a = 0 ?? 999;
console.log(a); // 0
console.log(Number.MAX_SAFE_INTEGER)
// 9007199254740991
console.log(Number.MIN_SAFE_INTEGER)
// -9007199254740991