<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>
因为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}`);
r,g,b都是else代码块中的临时变量,到17行肯定不认识啊。将r,g,b的定义和日志语句放到同一个层级才能访问到
修改代码如下
<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)
color = `rgb(${r},${g},${b})`
}
console.log(color);
</script>
因为 r 写在了 else 里面,所以外面不能调用
flag 是true,只会走if,不走else啊
该回答引用GPTᴼᴾᴱᴺᴬᴵ
在代码中,如果flag为true,则会在循环中为color变量赋值。如果flag为false,则不会执行该赋值语句块,这就导致了在后面的console.log()语句中,r、g、b变量没有被定义。你可以将 let r = Math.floor(Math.random() * 256)、let g = Math.floor(Math.random() * 256)、let b = Math.floor(Math.random() * 256)这几行代码移动到if语句块的外面,这样就可以保证不管flag的值是true还是false,r、g、b这三个变量都会被定义。