为何JavaScript函数仅返回单个结果且始终输出固定字符串?
问题解答
一、为什么函数仅返回单个语句?
因为return语句的作用是立即终止函数执行并返回结果。你的函数里,循环第一次执行(i=0)时就触发了return,函数直接退出,根本不会继续运行后续的循环迭代,所以只会返回第一个触发的结果,不会输出其他内容。
二、为什么始终返回"Why is the ground shaking"?
原因有两个:
- 循环从
i=0开始,而0除以任何非零整数的余数都是0,所以i%7==0 && i%9==0这个条件在第一次循环就成立,直接返回对应字符串。 - 你的函数完全没用到传入的
number参数!不管你传9、4还是其他值,函数内部都是在循环判断i的值,和输入参数毫无关系。
修正建议(根据常见需求调整)
需求1:判断传入的number是否符合条件
如果你的目标是根据输入的数字返回对应结果,不需要循环,直接判断参数即可:
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)); // 输出 "Here is the magic 9" console.log(message(4)); // 输出 "You have failed" console.log(message(63)); // 输出 "Why is the ground shaking" console.log(message(21)); // 输出 "Here is the magic 7"
需求2:遍历0-199的所有数,收集所有结果
如果你的目标是遍历范围内的每个数字并返回全部结果,需要把结果存入数组,最后统一返回:
const message = function () { const results = []; for (let i = 0; i < 200; i++) { if (i % 7 === 0 && i % 9 === 0) { results.push("Why is the ground shaking"); } else if (i % 7 === 0) { results.push("Here is the magic 7"); } else if (i % 9 === 0) { results.push("Here is the magic 9"); } else { results.push("You have failed"); } } return results; }; console.log(message()); // 返回包含200个元素的数组,对应每个数字的结果
内容的提问来源于stack exchange,提问作者user19586856
相关产品推荐
相关产品推荐

