译者:全凭一口仙气儿活着
(广告,请不要阻止。)
9. 变量和赋值
JavaScript声明变量的主要方式:
-
let 声明可变的变量。
-
const 声明常量(不可变变量)。
在ES6之前,还有var。但它有几个怪癖,所以最好在现代JavaScript中避免它。您可以在“Speaking JavaScript”中阅读更多相关信息。
9.1. let
通过let声明的变量是可变的:
let i;
i = 0;
i = i + 1;
assert.equal(i, 1);
你可以同时声明和复制:
let i = 0;
9.2. const
通过const声明的变量是不可变的。您必须立即初始化:
const i = 0; // must initialize
assert.throws(
() => { i = i + 1 },
{
name: 'TypeError',
message: 'Assignment to constant variable.',
}
);
9.2.1. const and 不变
在JavaScript中,const仅表示指针(变量名和变量值之间的关联)是不可变的。值本身可能是可变的,如下例中的obj。
const obj = { prop: 0 };
obj.prop = obj.prop + 1;
assert.equal(obj.prop, 1);
然而:
const obj = { prop: 0 };
assert.throws(
() => { obj = {} },
{
name: 'TypeError',
message: 'Assignment to constant variable.',
}
);
9.2.2. const and循环
你可以将const与for-of循环一起使用,每次迭代都会创建一个新的绑定:
const arr = ['hello', 'world'];
for (const elem of arr) {
console.log(elem);
}
// Output:
// 'hello'
// 'world'
在plain for循环中,必须使用let,但是:
const arr = ['hello', 'world'];
for (let i=0; i<arr.length; i++) {
const elem = arr[i];
console.log(elem);
}
9.3. let和 const的选择
我建议使用以下规则来选择let和const::
-
const表示不可变绑定,并且变量永远不会更改其值。优先用他.
-
let 表示变量的值发生变化。仅在不能使用const时才使用它。
Exercise: const
exercises/variables-assignment/const_exrc.js
9.4.变量的作用域
变量的作用域指的是可以访问它的区域.
与大多数现代编程语言一样,通过let和const声明的变量是有块级作用域的:它们只能在声明的块中访问它们。
{
const x = 0;
}
assert.throws(
() => x + 1,
{
name: 'ReferenceError',
message: 'x is not defined',
}
);
花括号包含一个代码块。 x仅存在于该块中,外部不能访问。
9.4.1.覆盖和 块
您不能在同一级别声明两次相同的变量。但是,您可以嵌套块并使用在块外部使用的相同变量名x:
const x = 1;
assert.equal(x, 1);
{
const x = 2;
assert.equal(x, 2);
}
assert.equal(x, 1);
在块的内部,内部的x的名称是唯一的。内部的X会覆盖掉外部的X。在外部访问,可以访问懂啊外部的x。
有关变量范围和闭包的更多信息
有关可变范围和闭包的更多信息,请参阅本书后面的相应章节the corresponding chapter 。
测验
Next: [10. Values](