JavaScript函数可正常运行却输出undefined,原因是什么?
为什么第一个脚本会输出undefined?
核心原因很简单:JavaScript中,没有显式写return语句的函数,默认返回undefined。
第一个代码的问题分析
看你第一段代码里的total函数:
function total() { if (price > 250) { var result = price * discount; var cost = price - result; console.log("your total cost will be " + cost); } else { console.log("your total cost will be " + price) } }
这个函数里只有console.log语句,完全没有return。当你调用total()时,函数执行完内部的console.log后,会默认返回undefined。
而你最后一行写了console.log(total());,相当于把total()的返回值(也就是undefined)再打印一遍,所以控制台会出现两次输出:一次是函数内部console.log的计算结果,另一次就是这个额外的undefined。
第二个代码解决问题的原因
第二段代码里你把console.log换成了return:
function total() { if (price > 250) { var result = price * discount; var cost = price - result; return ("your total cost will be " + cost); } else { return ("your total cost will be " + price) } }
这时候total()执行后会返回你拼接好的字符串,console.log(total())就会直接打印这个字符串,不会再输出undefined了。
额外小建议
prompt()返回的是字符串类型,直接和数字250比较可能会有潜在问题(比如输入"1000"和250比较时,字符串比较规则和数字不同),建议转成数字后再使用:
let price = Number(prompt("What is the total cost? "));
内容的提问来源于stack exchange,提问作者shiftedReality
相关产品推荐
相关产品推荐

