You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript函数返回随机数时遇执行问题,求技术解析

问题原因与解决办法

你的代码里有个核心问题:return语句会直接终止函数执行,它后面的代码永远不会被运行。

看你的recordLog函数:

function recordLog (){
    MyButton.style.backgroundColor = 'red';
        
    let RandomNumber = Math.floor(Math.random() * 256);
        
    return RandomNumber; // 函数在这里就结束了
    console.log(RandomNumber); // 这行代码永远不会执行
};

修正方案

把console.log移到return前面,这样既能打印随机数,也能正常返回值:

function recordLog (){
    MyButton.style.backgroundColor = 'red';
        
    let RandomNumber = Math.floor(Math.random() * 256);
        
    console.log(RandomNumber); // 先执行打印
    return RandomNumber; // 再返回数值
};

如果你的需求只是在控制台输出随机数,不需要返回值,直接删掉return语句也能达到目的。

内容的提问来源于stack exchange,提问作者Andrzej Polachow

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 12:49:58