【问题标题】:Why is my Node.js if else condition not recognized? [duplicate]如果无法识别其他条件,为什么我的 Node.js? [复制]
【发布时间】:2020-03-22 09:37:43
【问题描述】:

我的代码

console.log('Starting app');

const fs = require('fs');
const os = require('os');
const _ = require('lodash');

const notes = require('./notes.js');

var command = process.argv[2];
console.log(command);


if (Comment = 'add') {
    console.log('adding new note');
  } else if (command = 'list') {
    console.log('listing all notes');
  } else {
    console.log('command not recognized');
  }

当我跑步时

 node app.js list

我明白了

Starting app
Starting node.js
list
adding new note

我的 else if 语句有什么问题?

【问题讨论】:

  • Comment = 'add' 不是比较,而是分配。它的值是赋值后Comment 的值(即'add'),它永远不会为假。阅读JavaScript operators
  • if (Comment = 'add') -> if (command == 'add')
  • 本题不涉及Node.js。
  • 好的,它来自 Node.js 书,但是 javascipt 语法。

标签: javascript node.js


【解决方案1】:

= 是赋值运算符。您正在分配 'add'Comment,然后检查该值是否在布尔上下文中计算为true,它当然会这样做。您应该使用=== 运算符:

if (Comment === 'add') {
    // Here-^

另外,Comment 也没有在任何地方声明,这将导致ReferenceError 并使您的进程崩溃。

【讨论】:

  • 因回答明显重复而被否决。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-09-02
  • 1970-01-01
  • 2017-05-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多