node14下测试
错
if (a) {
console.log("a is exists")
} else {
console.log("a is not exists")
}
错(已定义未赋值的情况下这种写法才能执行)
if (a !== undefined) {
console.log("a is exists")
} else {
console.log("a is not exists")
}
对(已定义未赋值,此时变量值为undefined)
let a
if ( a !== undefined ) {
console.log("a is exists")
} else {
console.log("a is not exists")
}
对
if (typeof a !== 'undefined') {
console.log("a is exists")
} else {
console.log("a is not exists")
}
对(全局变量)
如果是浏览器此处global应换为window,app和小程序参考具体平台说明
if ( global.a ) {
console.log("a is exists")
} else {
console.log("a is not exists")
}
es2020中提供了globalThis来统一不同环境中的关键词,可在所有支持es2020的环境中使用
if ( globalThis.a ) {
console.log("a is exists")
} else {
console.log("a is not exists")
}
对(局部变量)
(function () {
// let a = 123
if ( this.a ) {
console.log("a is exists")
} else {
console.log("a is not exists")
}
})()
给变量指定默认值
对(已定义未赋值)
let a
let b = a || 'world'
let a
let b = a ?? 'world'
对(局部变量)
(function () {
let b = this.a || 'world'
})()
(function () {
let b = this.a ?? 'world'
})()
错
let b = a || 'world'
let b = a ?? 'world'
注意:
其中||
不能用于布尔值,建议使用??
空值合并(Nullish coalescing),??
是es2020语法,vue2模板中尚不支持(vue3是可以的,https://github.com/vuejs/vue/issues/11088),另外es2020中的可选链(Optional chaining)也是极为有用的。
vue模板中不要引用全局变量(会发出警告),应只引用data和computed中定义的响应式变量,亦不能在vue模板中使用未定义的响应式变量。