js判断变量是否存在及默认值的使用

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模板中使用未定义的响应式变量。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容