let实际上为 JavaScript 新增了块级作用域。
{
let a = 10;
var b = 1;
}
a // ReferenceError: a is not defined.
b // 1
const声明一个只读的常量。一旦声明,常量的值就不能改变。
const PI = 3.1415;
PI // 3.1415
PI = 3; // TypeError: Assignment to constant variable.
# 解构赋值
ES6 允许按照一定模式,从数组和对象中提取值,对变量进行赋值,这被称为解构(Destructuring)
```ecmascript 6
// 数组
let [a, b, c] = [1, 2, 3];
// 指定默认值
let [x, y = 'b'] = ['a']; // x='a', y='b'
x // 'a'
y // 'b'
// 对象
let { foo, bar } = { foo: "aaa", bar: "bbb" };
foo // "aaa"
bar // "bbb"
// 属性别名
let { foo: baz } = { foo: 'aaa' };
baz // "aaa"
// 函数参数
function add([x, y]){
return x + y;
}
function add2({ x, y }){
return x + y;
}
add([1, 2]); // 3
add2({ x: 1, y: 2}); // 3
扩展运算符(spread)是三个点(…)。它好比 rest 参数的逆运算,将一个数组转为用逗号分隔的参数序列。
console.log(...[1, 2, 3])
// 1 2 3
console.log(1, ...[2, 3, 4], 5)
// 1 2 3 4 5
// 函数
function add(x, y) {
return x + y;
}
const numbers = [4, 38];
add(...numbers) // 42
模板字符串(template string)是增强版的字符串,用反引号(`)标识。它可以当作普通字符串使用,也可以用来定义多行字符串,或者在字符串中嵌入变量。
let name = "Bob", time = "today";
let s = `Hello ${name}, how are you ${time}?`
s // 'Hello Bob, how are you today?'
// 默认值
function log(x, y = 'World') {
console.log(x, y);
}
log('Hello') // Hello World
log('Hello', 'China') // Hello China
// 解构赋值
function foo({x, y = 5}) {
console.log(x, y);
}
foo({x: 1}) // 1 5
function add(...values) {
let sum = 0;
for (var val of values) {
sum += val;
}
return sum;
}
add(2, 5, 3) // 10
var sum = (num1, num2) => { return num1 + num2; }
// 等同于
var sum = function(sum1, sum2) {
return sum1 + sum2;
}
注意点:
doing