NodeJS / JavaScript if 语句不起作用

NodeJS / JavaScript if statement not working

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' 进行比较)。

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

我更喜欢检查

if(!qData.osType)

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

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