存储随机数的全局变量的奇怪行为

我刚刚开始练习javascript,因此我尝试制作一些非常简单的js应用程序,以便可以习惯这种语言。

Here I was trying to make a very simple change body background with a button. This was my first attempt.

const btn = document.querySelector(".btn");
const colors = ["#e67e22", "#2980b9", "#16a085", "#2c3e50", "#9b59b6"];
let randomNumber = Math.floor(Math.random() * 5);

function changeBg() {
  document.body.style.backgroundColor = colors[randomNumber];
}

btn.addEventListener("click", changeBg);

What this does is to change the bg-color with a random number from 0 to 4 but only once, ofc I don't want that..

但是在我这样做之后,它就起作用了。

const btn = document.querySelector(".btn");
const colors = ["#e67e22", "#2980b9", "#16a085", "#2c3e50", "#9b59b6"];

function changeBg() {
  let randomNumber = Math.floor(Math.random() * 5);
  document.body.style.backgroundColor = colors[randomNumber];
}

btn.addEventListener("click", changeBg);

我想找出的是为什么会这样?我想念什么吗?

评论