为什么在全局范围的for-of循环中使用const会引发TypeError,但在函数内却起作用?

时间:2019-01-10 04:09:19

标签: javascript const typeerror

var tests = [1, 4, 3];
for(const test of tests){
  test += 1;
  console.log(test);
}

-我们得到const的类型错误b / c

function average(...nums){
  let sum = 0;
  let counter = 0;
  for(const num of nums){
    sum += num;
    counter++;
  }
  return sum / counter;
}

console.log(average(5, 5));

-为什么由于再次使用const而在这里没有类型错误

2 个答案:

答案 0 :(得分:1)

因为您要在第一个而不是第二个中重新分配给常量。您将print('Welcome to Rock, Paper, and Scissors. You know the rules already. But, we will play for as long as you want. If you win more rounds, then you survive. If I win though, well... you already know.') while True: w = input('Choose a weapon(r for rock, p for paper, s for scissors, q for quit)!: ').lower() print("W: ", w) if w == 'q': break elif w == 'r' or w == 'p' or w == 's': if game(w): memory(w, fingers) respond(numrock, numpaper, numscissors) hand1(fingers) else: print("Incorrect Option! Please try again.") continue 更改为test是非法的,而您从未更改过test += 1。如果您第二次尝试num,则会遇到同样的问题。

答案 1 :(得分:0)

我认为您对要更改哪个变量有些困惑。 第一个您要更改const test的值,但是在第二个示例中,您要更改let sum

的值

sum += num;sum = sum + num相同,num保持不变

test += 1;test = test + 1