![](/img/trans.png)
[英]Why does this function return only true, since there is no else statement to make it return false under a non true condition?
[英]Why does function only return on statement and not the others
所以我下面的功能是
const message = function (number) {
for (let i = 0; i < 200; i++) {
if (i % 7 == 0 && i % 9 == 0) {
return "Why is the ground shaking";
} else if (i % 7 == 0) {
return "Here is the magic 7";
} else if (i % 9 == 0) {
return "Here is the magic 9";
} else {
return "You have failed";
}
}
};
console.log(message(9));
console.log(message(4));
console.log(message(36));
console.log(message(21));
但它总是返回“为什么地面在晃动”不知道为什么
你应该把i = number
而不是i = 0
const message = function (number) { for (let i = number; i < 200; i++) { if (i % 7 == 0 && i % 9 == 0) { return "Why is the ground shaking"; } else if (i % 7 == 0) { return "Here is the magic 7"; } else if (i % 9 == 0) { return "Here is the magic 9"; } else { return "You have failed"; } } }; console.log(message(9)); console.log(message(4)); console.log(message(36)); console.log(message(21));
正如评论部分中提到的, for
循环在这里是多余的。
你的message(number)
函数有 1 个参数,即number
,如果你有if - else
和return
语句,你的循环只会在每个函数调用上执行一次(当return
发生时)。 你可以把i < 1
或i < 2000
,结果是一样的。
所以你可以做的是,删除循环,并简单地将你的参数(number)
而不是i
放在你的每个if
语句中。
我不是最擅长解释,但希望这会有所帮助。
const message = function (number) { if (number % 7 == 0 && number % 9 == 0) { return "Why is the ground shaking"; } else if (number % 7 == 0) { return "Here is the magic 7"; } else if (number % 9 == 0) { return "Here is the magic 9"; } else { return "You have failed"; } }; console.log(message(9)); console.log(message(4)); console.log(message(36)); console.log(message(21));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.