JS函数无法自主输出,调用时同时打印undefined与目标值问题
问题原因与解决方案
一、为什么console.log(randphrase())会额外打印undefined
你的randphrase函数内部通过console.log输出幸运语,但函数本身没有任何return语句。在JavaScript中,没有明确返回值的函数默认会返回undefined。当你调用console.log(randphrase())时,会先执行randphrase(),触发它内部的console.log输出幸运语,随后console.log会把randphrase()的返回值(也就是undefined)打印出来,所以会看到额外的undefined。
二、为什么直接调用randphrase()大多时候没有输出
你的randnum函数每次调用都会生成一个0~7之间的随机整数(Math.random() * 8的范围是0 ≤ x < 8,Math.floor后得到0-7),而且在randphrase的if-else分支里,每个判断都会重新调用一次randnum(),意味着每个分支用的都是不同的随机数。
比如第一个判断用了一个随机数,不管是否命中0,第二个判断又会生成新的随机数判断是否为1,以此类推。更关键的是,随机数有一半概率落在4-7之间,这时候所有分支的条件都不满足,函数内部没有任何console.log执行,自然就没有输出。
三、修正后的代码
方案1:函数内部直接输出(推荐)
const goodfortunes = [ ' You will be rich', ' You will live a long life', ' Wednesday looking lucky', ' You have good luck today' ] // 生成和数组长度匹配的随机索引,避免无效范围 let randnum = () => Math.floor(Math.random() * goodfortunes.length); let randphrase = () => { // 只生成一次随机数,避免多次调用导致的判断混乱 const index = randnum(); console.log(goodfortunes[index]); } // 直接调用函数即可输出,无需套console.log randphrase();
方案2:函数返回结果,外部控制打印
const goodfortunes = [ ' You will be rich', ' You will live a long life', ' Wednesday looking lucky', ' You have good luck today' ] let randnum = () => Math.floor(Math.random() * goodfortunes.length); let randphrase = () => { const index = randnum(); return goodfortunes[index]; } // 外部打印返回值,不会出现undefined console.log(randphrase());
内容的提问来源于stack exchange,提问作者yurgburg
相关产品推荐
相关产品推荐

