一.let命令
1. 基本用法
ES6新增了let命令,用来声明变量。它的用法类似于var,但由它声明的变量,只在let命令所在的代码块内有效。
let a;
let a,b,c;
let a = 1,b = 'hello',c = [];
2. 特点
1. let命令只在声明所在的块级作用域内有效。
{
var a = 1;
let b = 10;
}
console.log("a",a); // a 1
console.log("b",b); // b is not defined -- Error
2. let必需先声明、后使用。
var tmp = new Date();
function f() {
console.log("111",tmp); // tmp is not defined -- Error
let tmp = "hello world"; // 如果把这里的let改为var,上一行结果为undefined
console.log("222",tmp);
}
f();
3. let声明的变量不可重复声明。
var message = "Hello!";
var age = 25;
// 以下两行都会报错
let message = "Hi!";
const age = 30;
二.const命令
1.const声明一个只读的常量。一旦声明,常量的值就不能改变。(不可变只是针对其地址,不针对地址指向的内容,如数组,改变数组内的值是可以的,但是不能把别的数组赋值给原数组)
const PI = 3.1415;
console.log(PI); // 3.1415
PI = 3; // Assignment to constant variable.
2. const一旦声明变量,就必须立即初始化,不能在后续赋值。对于const 常量来说,只声明不赋值,就会报错
if (true) {
const MAX = 5;
}
console.log(MAX); // MAX is not defined
三. 解构赋值
1.数组
// 一维数组
let [a, , c] = [1, 2, 3]; //a =1, c= 3
let [a] = [1, 2, 3]; //a =1
let [a, b] = [1]; //a =1, b=undefined
let[x = 'a'] = []; // x=a
let [x = 'a'] = ['sss']; // x=sss
// 多维数组
let [a, [[b], c]] = [1, [[2], 3]];
a // 1
b // 2
c // 3
// 解构失败(等号两边的模式不同):
let [a, [b]] = [1];
console.log(a);
console.log(b);
2.对象
// 根据对象的key对应
let { username: user, password : pass} = { username: "aaa", password: "bbb"}
//let { username, password } = { username: "aaa", password: "bbb" };
console.log(user); //aaa
console.log(pass); //bbb
3.字符串
const [a,b,c,d,e] = "hello";
console.log(a,b,c,d,e);
// 数组、类似数组的对象都有一个length属性,
let {length : len01} = [1,2,3,4,5];
console.log(len01);
let {length : len02} = 'hello';
console.log(len02);
4.遍历map
var map = new Map();
map.set('first', 'hello');
map.set('second', 'world');
for (let [key, value] of map) {
console.log(key + " is " + value);
}
5.字符串模板
// 传统的JavaScript语言,输出模板通常是这样写的。
$('#result').append(
'There are <b>' + basket.count + '</b> ' +
'items in your basket, ' +
'<em>' + basket.onSale +
'</em> are on sale!'
);
// 这种写法相当繁琐不方便,各种引号 加号 转义符号 效率低
// ES6引入了模板字符串解决这个问题。
$('#result').append(`
There are <b>${basket.count}</b> items
in your basket, <em>${basket.onSale}</em>
are on sale!
`);
6.函数参数默认值
function Point(x = 0, y = 0) {
this.x = x;
this.y = y;
}
let p = new Point();
console.log(p);// 0,0
p = new Point(1,2);
console.log(p);1,2
7. rest参数
类似于java语法
function f02(a,...values) {
let sum = 0;
for (let val of values) {
sum += val;
}
return sum;
}
let result = f02(2, 5, 8,5,5) // 23
console.log(result);
function f02(a, ...values, b) { //在末尾写参数会报错
let sum = 0;
for (let val of values) {
sum += val;
}
return sum;
}
let result = f02(2, 5, 8, 5, 5) //Rest parameter must be last formal parameter
console.log(result);
// 函数的length属性代表函数的参数个数。
// length属性,不包括已指定默认值的参数
// length属性,不包括rest参数。
let len = (function(a) {}).length; // 1
console.log(len);
len = (function (a = 5) {}).length; // 0
console.log(len);
len =(function (a, b, c = 5) {}).length; // 2
console.log(len);
len =(function(...a) {}).length; // 0
console.log(len);
len = (function(a, ...b) {}).length ; // 1
console.log(len);
//可理解为必传的参数个数
应用:
√ 复制数组
const a1 = [1, 2];
// 写法一
const a2 = [...a1];
// 写法二
const [...a3] = a1;
√ 合并数组
// 扩展运算符提供了数组合并的新写法。
let arr1 = ['a', 'b'];
let arr2 = ['c'];
let arr3 = ['d', 'e'];
// ES5的合并数组
let result = arr1.concat(arr2, arr3);
// [ 'a', 'b', 'c', 'd', 'e' ]
// ES6的合并数组
result = [...arr1, ...arr2, ...arr3]
// [ 'a', 'b', 'c', 'd', 'e' ]
√ 字符串
扩展运算符还可以将字符串转为真正的数组。
let arr = [...'hello']
console.log(arr); // [ "h", "e", "l", "l", "o" ]
8. 箭头函数
语法和java类似
let f = () => 5;
// 等同于
let f = function () { return 5 };
let sum = (num1, num2) => num1 + num2;
// 等同于
let sum = function(num1, num2) {
return num1 + num2;
};
// 如果箭头函数的代码块不仅只有return语句,就要使用语句块将它们括起来。
let sum = (num1, num2) => {
console.log(num1 + num2);
return num1 + num2;
};
// 由于大括号在箭头函数中被解释为代码块,
// 所以如果箭头函数返回一个对象,必须在对象外面加上括号。
let getTempItem = id => ({ id: id, name: "Temp" });
// 等同于
let getTempItem = function (id) {
return { id: id, name: "Temp" }
};
9. Iterator和for...of循环
for (let v in arr) {
console.log(v); //获取的map的‘key’,数组的下标
}
for (let v of arr) {
console.log(v);//获取的‘value’
}
10.Promise对象
let promise = new Promise(function (resolve, reject) {
// ... some code
if (/*异步操作成功*/ ) {
resolve(value);
} else {
reject(error);
}
});
//写法一
promise.then(
function(value) {
// success code
},
function(error) {
// failure code
});
//写法二
promise.then(
function(value) {
// success code
}).catch(
function(error) {
// failure code
}
);
11.module (import 和export)
js中也可以导出别的js, 例如:import x from '../xxx.js'
let A = '导出常量666';
let fun = function() { //function fun(){
console.log('导出方法')
};
let student={
name:'xxm',
age:'18'
}
export {A,fun,student}
//es6
<script type="module">
import {
A,fun,student
} from './js/module01.js';
console.log(A)
console.log(student)
fun()
</script>
或者
let A = '导出常量666';
let fun = function() {
console.log('导出方法')
};
let student={
name:'xxm',
age:'18'
}
export default {A,fun,student}
//es6
<script type="module">
import xxm from './js/module01.js';//这种写法js导出用export default {xxx,xxx,xxx}
console.log(xxm.A)
console.log(xxm.student)
xxm.fun()
</script>