javascript - if 语句运行在 false 上?

标签 javascript

使用 JavaScript

我有一个函数

function test(variable)
{
  if(variable != 'undefined')
  {
     console.log('variable is not set');
     console.log('variable', where); 
  }
}

我使用test();来调用它

但在控制台中我得到 '哪里没有设置' '其中设置为未定义'

为什么?


更新 这个功能不是我实际使用的。

如果变量未定义,函数不应执行任何操作。

该示例是为了显示 if 语句不起作用。

但问题实际上是我使用 if variable != 'undefined' 而不是 variable != undefined

最佳答案

您在同一个 if 分支中有两个 console.log 调用。改为这样做:

function test(variable)
{
  if(variable != 'undefined')
  {
     console.log('where is not set');
  }
  else
  {
     console.log('where is set as ', where); 
  }
}

除此之外:如果您想测试变量是否未定义,请使用 typeof operator测试类型:typeof variable!= 'undefined'。目前,您只需测试 variable 是否不等于字符串值 'undefined'

关于javascript - if 语句运行在 false 上?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3617498/

相关文章:

javascript - 将 ruby​​ 哈希转换为命名值的 javascript 数组

javascript - 字符串插值,如 scala.js 的 java.text.MessageFormat

javascript - 使用 jQuery 我想在 TD 悬停时突出显示表中的列

javascript - 为什么这段 jQuery 代码不起作用?

javascript - 无法从 JSONArray 对象获取值,我只是 forEach 、 ItemFileReadStore、JSON.parse

javascript - 使用 v8 读取二进制文件的函数

javascript - 我的自定义维度和指标未显示在 Google Analytics(分析)中?

javascript - window.onload 的替代品

javascript - 如何检查 props 中的元素是否匹配条件?

javascript - 如何在初始化 ServiceWorker 时声明客户端以避免重新加载页面?