0

我正在向 MDN 学习,所以这里有这样的代码,这让我大吃一惊,为什么 line 中的 choice变量在const choice = select.value;这里被用作常量。我相信这.value可能是改变,并且常量在赋值后不能改变......或者重新声明变量会导致错误......每次,我改变选择值,它调用setWeather函数,对吗?那么,那里发生了什么,有人可以解释一下吗?

const select = document.querySelector('select');
const para = document.querySelector('p');

select.addEventListener('change', setWeather);

function setWeather() {
  const choice = select.value;

  if (choice === 'sunny') {
    para.textContent = 'It is nice and sunny outside today. Wear shorts! Go to the beach, or the park, and get an ice cream.';
  } else if (choice === 'rainy') {
    para.textContent = 'Rain is falling outside; take a rain coat and an umbrella, and don\'t stay out for too long.';
  } else if (choice === 'snowing') {
    para.textContent = 'The snow is coming down — it is freezing! Best to stay in with a cup of hot chocolate, or go build a snowman.';
  } else if (choice === 'overcast') {
    para.textContent = 'It isn\'t raining, but the sky is grey and gloomy; it could turn any minute, so take a rain coat just in case.';
  } else {
    para.textContent = '';
  }
}

还有来自 MDN 网站的链接https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/conditionals

4

2 回答 2

1

查看 const 变量的范围,它的生命只在函数运行时存在,并在函数完成时结束,因此当再次调用函数时,它是一个新变量,它被分配了值。您必须了解变量的范围。

于 2019-11-25T08:44:43.983 回答
0

const 声明创建对值的只读引用。这并不意味着它持有的值是不可变的,只是不能重新分配变量标识符。例如,在内容是对象的情况下,这意味着可以更改对象的内容(例如,它的属性)(有关更多详细信息,请访问:https ://developer.mozilla.org/en-US/docs/网页/JavaScript/参考/声明/常量)。

请找到下面的示例,就像“const select”一样,在这里我声明了一个名为“car”的对象类型的 const 变量,并且我可以更改“car”对象的属性“model”:

const car = {type:"Fiat", model:"500", color:"white"};
  car.model= "EX60";
  console.log(car);

于 2019-11-25T09:05:07.887 回答