javascript - 没有参数的条件语句

标签 javascript

我正在尝试学习 JavaScript 中的条件语句,当我在不传递任何参数的情况下调用函数时,我仍然得到 x 等于 y。我不明白我在哪里遗漏了代码。

function tryMe(x, y) {
  if (x == y) {
    console.log("x and y are equal");
  } else if (x > y) {
    console.log("x is greater than y");
  } else if (x < y) {
    console.log("x is less than y")
  } else {
    console.log("no values")
  }
}

tryMe();

这是我的控制台日志:

x and y are equal // i am expecting it to console.log("no values")

最佳答案

发生这种情况是因为当您调用 tryMe() 时,xy 都是 undefined,这意味着它们是平等的。因此,您需要先检查是否有值分配给 xy

function tryMe(x, y) {
  if (typeof(x) != 'undefined' && typeof(y) != 'undefined') {
    if (x == y) {
      console.log("x and y are equal");
    } else if (x > y) {
      console.log("x is greater than y");
    } else if (x < y) {
      console.log("x is less than y")
    } else {
      console.log("no values")
    }
  } else {
    console.log("no values")
  }
}

tryMe();
tryMe(1);
tryMe(1, 2);

关于javascript - 没有参数的条件语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56963683/

相关文章:

javascript - 使用 javascript 拆分 html 表值

javascript - 使用 .NET/C# 与使用 HTML/JavaScript 构建 Android 应用程序

javascript - 多折线图不适用于日期格式

javascript - 如何在 textarea 中使用 google-code-prettify

javascript - 在 Angular Directive(指令)中组合两个事件处理程序

javascript - 如何将 AJAX 请求中的数据写入 VUE JS 中的数据?

javascript - Vuex/Vuejs : accessing localStorage within vuex store

javascript - 如何创建圆形导航系统?

javascript - 这个 javascript 连接对我有用一次,但是这总是可以接受的 javascript 吗?

javascript - 在 div 上设置 onchange 事件处理程序以运行更改尚不存在的表的函数