繁体   English   中英

为什么函数只返回语句而不返回其他语句

[英]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 循环

正如评论部分中提到的, for循环在这里是多余的。

你的message(number)函数有 1 个参数,即number ,如果你有if - elsereturn语句,你的循环只会在每个函数调用上执行一次(当return发生时)。 你可以把i < 1i < 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM