因为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}`);