为什么JS中evalInput函数的result变量无法保持数字类型?
问题根因
typeof(parseInt(_input)) === 'number'的判断逻辑完全无效:parseInt()的返回值永远是数字类型,就算入参无法转换为有效数字也会返回数字类型的NaN,而typeof NaN的结果就是'number',因此无论用户输入任何内容,if条件永远成立,else分支永远不会触发。- if分支中你直接将原始输入
_input赋值给了result,如果输入本身是字符串类型(比如测试时输入的d、或者用户输入字符串格式的数字'3'),result就会被直接覆盖为字符串类型,这就是你最终看到typeof result返回string的核心原因。 - 你输出的
typeof(typeof(parseInt(result))) = number属于异常结果:typeof的返回值本身就是字符串类型,嵌套两层typeof的结果理论上一定是'string',大概率是你输出时多写了一层typeof。
修复方案
你只需要确保给result赋值时使用转换后的数字类型值即可,修复后的代码如下:
function evalInput(_input) { // 默认值为数字0 var result = 0; // 先完成输入到数字的转换 const parsedInput = parseInt(_input); // 仅当转换结果为有效数字时才更新result if (!isNaN(parsedInput)) { if (parsedInput === 3) { launchHelp("./Help.txt"); } // 赋值转换后的数字,不直接使用原始输入值 result = parsedInput; } prompt("typeof(parseInt(result)) = " + typeof(parseInt(result))); prompt("typeof(result) = " + typeof(result)); return result; }
如果你不需要强制要求输入为整数,也可以把parseInt替换为Number()来兼容浮点数输入。
内容的提问来源于stack exchange,提问作者gendisarray
相关产品推荐
相关产品推荐

