一、ES6简介
ECMAScript 6.0(以下简称 ES6)是 JavaScript 语言的下一代标准,已经在 2015 年 6 月正式发布了。
那么ECMAScript 和 JavaScript 到底是什么关系?ECMAScript 和 JavaScript 的关系是,前者是后者的规格,后者是前者的一种实现。
二、let和const
1.let块级作用域
以前var声明的变量是函数作用作用域
if (true) {
var a = 10;
}
console.log(a); //10
现在let声明的变量具有块级作用域:{},也就是变量只在{}里面起作用,外面是无法获取和操作的
if (true) {
let a = 10;
}
console.log(a); //报错 a is not defined
2. let没有变量提升
console.log(num);//var声明的变量可以提前调用
var num = 10;
console.log(num);//let声明的变量不能提前使用
let num = 10;
3.const声明常量
const声明的常量里面的内容是不能更改的
三、解构赋值
1.数组结构
let [a, b, c] = [10, 20, 30];
console.log(a); //10
console.log(b); //20
console.log(c); //30
2.对象结构
let obj = { name: "tom", age: 23 };
let { name, age } = obj;
console.log(name);
console.log(age);
四、箭头函数
1.无参写法
原函数写法:
function fn() {
console.log("hello");
}
fn();
箭头函数写法:
const fn = () => console.log("hello");
fn();
2.单句写法
函数体中只有一句代码,代码的执行结果就是返回值的时候,可以省略箭头函数的大括号
原函数写法:
function sum(a, b) {
return a + b;
}
fn(10, 20);
箭头函数写法:
const fn = (a, b) => a + b;
console.log(fn(10, 20));
3.箭头函数中的this
普通函数中的this指向window
function fn() {
console.log(this); //window
}
fn();
对象中的普通函数执行调用者
var obj = {
name: "tom",
say: function() {
console.log(this);//obj对象
}
};
obj.say();
箭头函数中的this指的是函数定义位置的上下文。
var obj = {
name: "tom",
say: () => {
console.log(this);//window对象
}
};
obj.say();
面试题:
var name = "jim";
var obj = {
name: "tom",
say: () => {
console.log(this.name);
}
};
obj.say();
五、剩余参数
1.运用场景
比如我们想定义一个函数,如果是两个参数,就计算两个参数的和,如果是三个参数,就计算三个参数的和。
以前的写法:
function fn() {
var sum = 0;
// arguments是位数组,是函数中所有参数的形成的数组
for (var i = 0; i < arguments.length; i++) {
sum += arguments[i];
}
console.log(sum);
}
fn(10, 20); //30
fn(10, 20, 30); //60
Es6的写法:
const fn = (...args) => {
let sum = 0;
args.forEach(item => {
sum += item;
});
console.log(sum);
};
fn(10, 20); //30
fn(10, 20, 30); //60
2.使用场景
let arr1 = ["tom", "jim", "jack"];
let [str1, ...str2] = arr1;
console.log(str1); //tom
console.log(str2); //jim jack
六、扩展运算符
1.基础使用
扩展运算符是把数组或者对象转换成用逗号分隔的参数序列
let arr = ["tom", "jim", "jack"];
console.log(...arr); // tom jim jack
2.使用场景(合并数组)
let arr1 = ["a", "b", "c"];
let arr2 = ["d", "e", "f"];
let arr3 = [...arr1, ...arr2]; //['a','b','c','d','e','f']
console.log(arr3);
七、Array扩展
1.find方法
find是查找数组中符合条件的成员,如果没有找到返回undefined
let arr = [
{
id: "1",
name: "tom"
},
{
id: "2",
name: "jim"
}
];
const obj = arr.find(item => item.id == 2);
console.log(obj);
这个案例是查询对象的id是2的,返回结果是满足条件的那个对象
2.findIndex
findIndex是返回满足条件的索引号,查不到返回返回-1
let arr = [
{
id: "1",
name: "tom"
},
{
id: "2",
name: "jim"
}
];
const index = arr.findIndex(item => item.id == 3);
console.log(index);
3.includes
let arr = [10, 20, 30];
const res = arr.includes(10);
console.log(res);
上面判断的是10是不是在数组中存在
4.set
set类似于数组,但是成员中的值是唯一的,不会出现重复的
const set = new Set([10, 22, 22, 10, 5]);
set.add(11);
set.add(99);
set.delete(11);
console.log(...set);