我正在尝试学习 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()
时,x
和 y
都是 undefined
,这意味着它们是平等的。因此,您需要先检查是否有值分配给 x
和 y
。
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/