JS新手求助:自定义函数返回NaN而非预期数值问题排查
解决你的JavaScript函数NaN问题
嘿,我来帮你排查这个问题~ 你遇到的NaN问题,核心原因是**Math.max()和Math.min()无法直接处理逗号分隔的字符串**,咱们一步步拆解:
问题出在哪?
你原代码里把空格替换成逗号后,numbers变成了类似"1,2,3,4,5"的字符串,但Math.max()/Math.min()的要求是传入单独的数字参数(比如Math.max(1,2,3))或者用扩展运算符展开的数字数组。直接传字符串的话,JS没法把它解析成有效的数字,自然返回NaN。
修正方案
我们需要把输入的空格分隔字符串,先转成数字数组,再传给Math方法:
function highAndLow(numbers){ // 1. 按空格分割字符串,得到字符串数组 // 2. 把每个字符串元素转成数字类型 const numArr = numbers.split(' ').map(str => Number(str)); // 用扩展运算符...把数组元素逐个传给Math方法 const high = Math.max(...numArr); const min = Math.min(...numArr); const output = `The max value is ${high}, and the minimum is ${min}`; console.log(output); // 如果你需要函数调用时能拿到返回值,加上这行 return output; }; // 调用测试 console.log(highAndLow("1 2 3 4 5"));
额外小提示
你原函数没有return语句,所以调用console.log(highAndLow(...))时,除了函数内部的console.log输出,还会额外打印undefined(因为函数默认返回undefined)。如果需要让函数返回结果供后续使用,记得加上return output哦。
内容的提问来源于stack exchange,提问作者Mohammed Touati
相关产品推荐
相关产品推荐

