我试图学习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();Run Code Online (Sandbox Code Playgroud)
这是我的控制台日志:
x和y等于// //我期望它为console.log(“ no values”)
因为undefined等于undefined
当您不传递参数时,它都将变得不确定,x并且y
为什么会发生这种情况-当您只声明一个变量时,它具有默认值undefined。在您的情况下,发生的情况相同,您tryMe()声明了fn x,y并且具有默认值undefined,当您比较它们时,两者相等。
console.log(undefined == undefined)
var x, y
// Here you declared the variable which happens in your function
if(x === y) {
console.log('You never defined what value I have so Javascript engine put undefined by default')
}Run Code Online (Sandbox Code Playgroud)
发生这种情况的原因是,当您调用时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);Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
176 次 |
| 最近记录: |