js判断变量是否存在-检查js中是否存在变量

判断是否定义了变量

如果一个变量hog 在没有被定义的情况下被引用:

console.log(hoge) //ReferenceError: hoge is not defined

js判断变量是否存在-检查js中是否存在变量  第1张

它将产生一个“未定义”的错误。

js判断变量是否存在-检查js中是否存在变量  第2张

为了避免它可以使用typeof运算符检查变量是否存在。

const hoge = 'fuga'
if (typeof hoge !== 'undefined') {
  console.log(hoge) // fuga
  console.log(typeof hoge) // string
  console.log(typeof undefinedVarible) // undefined
}

如果对未定义项使用typeof运算符,将返回字符串“undefined”,因此可以进行判断变量是否存在。

js判断变量是否存在-检查js中是否存在变量  第3张

使用“ if (typeof variable !== 'undefined') ”检查变量是否存在。

if (typeof obj !== 'undefined') {
	// 如果存在变量
}else{
	// 如果变量不存在
}


本文来源:词雅网

本文地址:https://www.ciyawang.com/js-94.html

本文使用「 署名-非商业性使用-相同方式共享 4.0 国际 (CC BY-NC-SA 4.0) 」许可协议授权,转载或使用请署名并注明出处。

相关推荐