检查变量是否undefined(未定义)

var variable1 = 1;
if (typeof variable1 == 'undefined') {
    console.log('变量variable1未定义');
} else {
    console.log('变量variable1已定义'); // 变量variable1已定义
}


if (typeof variable2 == 'undefined') {
    console.log('变量variable2未定义'); // 变量variable2未定义
} else {
    console.log('变量variable2已定义');
}


var variable3 = 'hello, world';
variable3 = undefined // 将已声明且已赋值的变量设为undefined
if (typeof variable3 == 'undefined') {
    console.log('变量variable3未定义'); // 变量variable3未定义
} else {
    console.log('变量variable3已定义');
}


if (undefined == null) {
    console.log('undefined == null'); // undefined == null
} else {
    console.log('undefined != null');
}


if (undefined === null) {
    console.log('undefined === null');
} else {
    console.log('undefined !== null'); // undefined !== null
}


//========== 总结 ==========//
// 1、undefined和null一样都是一种值,所以undefined也是可以赋值给变量的。

Copyright © 2024 码农人生. All Rights Reserved