为什么JavaScript函数执行完成后会返回undefined?
为什么你的函数调用会输出undefined
你的randomNum函数里只有console.log语句,没有用return关键字返回任何值。在JavaScript里,只要函数没有明确写return语句,执行结束后就会默认返回undefined。
你写的console.log(randomNum(5))会分两步执行:
- 先运行
randomNum(5),函数内部打印ok; - 因为函数没返回值,所以
randomNum(5)的结果是undefined,外层的console.log就把这个结果也打印出来了。
如果不想看到多余的undefined,可以这么改:
- 直接调用函数,不用外层的
console.log:randomNum(5); // 只会输出'ok',不会出现undefined - 给函数加
return语句,让它返回指定内容(可选):function randomNum(n) { const numbers = [1,2,3,4,5,6,7,8,9,10] if(numbers.includes(n)) { console.log('ok'); return 'ok'; } else { console.log('Choose a value between 1 and 10'); return 'Choose a value between 1 and 10'; } } console.log(randomNum(5)); // 先打印'ok',再打印返回的'ok'
内容的提问来源于stack exchange,提问作者user20676816
相关产品推荐
相关产品推荐

