weixin_57756336 2023-03-13 16:20 采纳率: 84.6%
浏览 31
已结题

为什么log输出显示r未被定义呢


<script>
        let arr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', '7', '8']
        let color = '#'
        let flag = true
        if (flag) {
            for (let i = 1; i <= 6; i++) {
                let random = Math.floor(Math.random() * arr.length)
                color += arr[random]
            }
        } else {
            let r = Math.floor(Math.random() * 256)
            let g = Math.floor(Math.random() * 256)
            let b = Math.floor(Math.random() * 256)
        }
        console.log(color);
        console.log(`rgb${r},${g},${b}`);
    </script>

  • 写回答

6条回答 默认 最新

  • allyfireshen 2023-03-13 16:23
    关注

    因为r,g,b只定义在了else中,且使用let定义的变量只在当前代码块中有效,所以在else外输出的时候就会提示undefined,你可以改成var定义或者在外层定义:

    let arr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', '7', '8']
    let color = '#'
    let flag = true
    let r = 0, g = 0, b = 0
    
    if (flag) {
      for (let i = 1; i <= 6; i++) {
        let random = Math.floor(Math.random() * arr.length)
        color += arr[random]
      }
    } else {
      r = Math.floor(Math.random() * 256)
      g = Math.floor(Math.random() * 256)
      b = Math.floor(Math.random() * 256)
    
      // 或者
      var r = Math.floor(Math.random() * 256)
      var g = Math.floor(Math.random() * 256)
      var b = Math.floor(Math.random() * 256)
    }
    console.log(color);
    console.log(`rgb${r},${g},${b}`);
    
    
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论 编辑记录
查看更多回答(5条)

报告相同问题?

问题事件

  • 系统已结题 3月21日
  • 已采纳回答 3月13日
  • 创建了问题 3月13日

悬赏问题

  • ¥15 学习完python基础了,想继续学习该学习什么呢?
  • ¥15 itunes恢复数据最后一步发生错误
  • ¥15 关于#windows#的问题:2024年5月15日的win11更新后资源管理器没有地址栏了顶部的地址栏和文件搜索都消失了
  • ¥15 看一下OPENMV原理图有没有错误
  • ¥100 H5网页如何调用微信扫一扫功能?
  • ¥15 讲解电路图,付费求解
  • ¥15 有偿请教计算电磁学的问题涉及到空间中时域UTD和FDTD算法结合的
  • ¥15 vite打包后,页面出现h.createElement is not a function,但本地运行正常
  • ¥15 Java,消息推送配置
  • ¥15 Java计划序号重编制功能,此功能会对所有序号重新排序,排序后不改变前后置关系。