NodeJS / JavaScript if语句不工作

NodeJS / JavaScript if statement not working

本文关键字:工作 语句 if JavaScript NodeJS      更新时间:2023-09-26

NodeJS(最新).

我有下面的代码。为什么第一个IF语句没有按预期工作?控件不进入第一个IF语句。

我看到了下面代码中第一行的有效console.log输出,并期望第一个IF语句也应该执行它的代码。但事实并非如此;第二个IF语句生效

  console.log("-- inside create IP() qData['osType'] is set to :: " + qData['osType'])
  //--
  if ( qData['osType'] == 'undefined' ) {
    console.log("1 -- setting qData['osType'] = Linux by default for now. This should happen automatically.")
    qData['osType'] = 'Linux'
    console.log("1 -- inside create IP() if-statement-qData['osType'] and qData['osType'] is set to :: "+qData['osType'])
  }
  if ( typeof qData['osType'] == 'undefined' ) {
    console.log("2 -- setting qData['osType'] = Linux by default for now. This should happen automatically.")
    qData['osType'] = 'Linux'
    console.log("2 -- inside create IP() if-statement-qData['osType'] and qData['osType'] is set to :: "+qData['osType'])
  }
  qData['osType'] = 'Linux'
  //--

如果你正在检查未定义,你可以使用以下方法之一:

  • typeof foo === 'undefined'
  • foo === undefined
  • foo === void 0

其他任何内容实际上都不是(严格地)检查未定义的值(包括将值直接与字符串'undefined'进行比较)。

在您的第一个if语句中,qData['osType']计算为undefined,但您的比较正在检查undefined == "undefined"是否。字符串字面值有一个值,因此不等于undefined

在第二个if语句中,typeof qData['osType']求值为字符串"undefined",因此表达式求值为true,并执行代码块。

我想qData['osType'] == 'undefined'必须重写为qData['osType'] == undefined

我更喜欢检查

if(!qData.osType)