Const 重新声明 Javascript

Const Redeclaration Javascript

所以几周前我开始通过在线课程学习 Javascript。我已经到了开始学习 DOM 操作的地步,并且有一个练习可以为背景生成随机颜色。起初我将随机颜色保存到一个 let 变量中。但是当我看到练习的答案时,它使用了一个 const not let。这怎么可能,我还以为const不能重新声明呢?

 function randomColour() {
    const r = Math.floor(Math.random() * 255);
    const g = Math.floor(Math.random() * 255);
    const b = Math.floor(Math.random() * 255);
    return `rgb(${r},${g},${b}`;
 }

每当调用函数时,都会有一个新的环境记录,其中存储了函数中声明的所有变量。 const 变量只能存储一次。如果您再次调用该函数,则会有一条新记录,因此该变量可以保存另一个值。

 function a() {
   const b = Math.random();
    // assigning b again here won't work
 }

 a();  
 a(); // new record, new value