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'
//--发布于 2016-07-02 00:32:59
如果您正在检查未定义的-ness,您可以执行以下操作之一:
typeof foo === 'undefined'foo === undefinedfoo === void 0其他任何内容实际上都不是(严格地)检查未定义的值(包括直接将值与字符串'undefined'进行比较)。
发布于 2016-07-02 00:34:15
在您的第一个if语句中,qData['osType']的计算结果为undefined,但是您的比较是检查undefined == "undefined"是否。字符串文字有一个值,因此不等于undefined。
在第二个if语句中,typeof qData['osType']计算为字符串"undefined",因此表达式计算为true,并执行代码块。
发布于 2016-07-02 00:33:34
我认为qData['osType'] == 'undefined'必须重写为qData['osType'] == undefined
我更喜欢检查
if(!qData.osType)https://stackoverflow.com/questions/38155023
复制相似问题