首页 > 解决方案 > 如果条件与三元运算符不返回真或假

问题描述

我正在比较 Nodejs 中的 2 个对象属性

 if(alteredItem.main != (result.main)?result.main:"NULL"){

我在 VSCODE 中使用调试模式,所以当我检查时:

alteredItem.main = "232"
result.main = "232"

因此,我期望上述条件的结果是,False但我的调试控制台显示该值为:

"NULL"

如果我删除三元运算符并将条件更改为:

if(alteredItem.main != result.main){

这确实返回false

为什么"NULL"我使用三元运算符时它会返回?

标签: javascriptnode.js

解决方案


您正在混合使用if语句和三元表达式。你应该做一个/或,但不能同时做:

选项1:

if(alteredItem.main != result.main){
  return false;
} else {
  return 'NULL'
}

选项 2:

// It's unclear from your question what you're expecting
// the return value to be, this assumes you want to
// return either `false` or `'NULL'`
return alteredItem.main != result.main ? false : 'NULL';

推荐阅读