零零碎碎的学习ES6,总想对ES6有个小小的总结,用了几天的空余时间和参考大佬们的文章后终于有了个小小的总结,当然这只是ES6中比较常用的部分内容。
有些事现在不做以后就不可能会做了,好了,开始学习ES6
一、let 命令
二、const 命令
三、字符串模板
四、变量的解构赋值
五、扩展运算符和rest运算符
六、数组的知识
七、箭头函数
八、Set
九、Map
十、Promise
十一、class
十二、export 和 import
一、let 命令
在ES6之前,都是用 var
声明,但是它会变量提升成为全局变量。
function a() {
if (bool) {
var b = 'Hello ES6'
} else {
console.log(b)
}
}
其实是这样的
function a() {
var b
if (bool) {
b = 'Hello ES6'
} else {
//undefined
console.log(b)
}
//undefined
}
无论bool
的值是true
或 false
,b
都会被创建声明。
改写成let
function a() {
if (bool) {
let b = 'Hello ES6'
} else {
//ReferenceError: a is not defined.
console.log(b)
}
}
let
没有变量提升,它的作用域是当前所在的代码块
####块级作用域
ES5只有全局作用域和函数作用域,带来一些不合理的场景。
(1)、变量提升造成内部变量覆盖外层的变量
var status= true;
function st() {
if (false) {
var status = false;
}
console.log(status);
}
st(); //undefined
(2)、变量i
成为全局变量
var arr=[1,2,3,4,5,6];
for(var i=0;i<arr.length;i++){
...
}
console.log(i) //6
ES6块级作用域
function num() {
let n = 6;
if (true) {
let n = 7;
}
console.log(n); // 6
}
表明外层代码块不受内层代码块的影响,如果用 var
声明,最后的值是7。
内层作用域 可以 和 外层作用域 定义 同名 变量
{
let aa ='Hello Word';
{
let aa='Hello ES6';
}
}
相同作用域不能重复声明
// 报错
function func() {
let aa ='Hello Word';
let aa='Hello ES6';
}
// 报错
function func() {
let aa ='Hello Word';
var aa='Hello ES6';
}
二、const 命令
const 声明一个只读常量,并且常量的值不能改变。
const a='Hello Word';
a //Hello Word
a='Hello ES6'; //报错
const 声明的变量不能改变值,所以const 声明变量就必须初始化,不能以后赋值。
if (true) {
const a = 'Hello Word';
}
a //报错
const 只在声明的块级作用域内有效,不会变量提升。
三、模板字符串
1、用${name}
进行字符串拼接和运算
//ES5
var a = 'ES5';
var b = '一起学习' + a + 'go';
//ES6
let c = 'ES6';
let d = `一起学习${c}go`;
//运算
let e = 1;
let f = 2;
let result = `${e+f}`;
2、常用方法
const es6 = 'hello es6'
//includes 是否存在
console.log(es6.includes('h')) // true
//startsWith 判断开头
console.log(es6.startsWith('hello')) // true
//endsWith 判断结尾
console.log(es6.endsWith('!')) // true
// repeat: 复制字符串 如果你是小数, Math.floor(num) 来处理
console.log(es6.repeat(2)) // 'hello es6hello es6'
console.log(es6.repeat(3.6)) // 'hello es6hello es6hello es6'
四、变量的解构赋值
从数组和对象中提取值,对变量进行赋值,这被称为解构。
//对象
let {name, age} = {name: 'ES6', age: '3'};
name //ES6
age //3
//数组
let [a, b, c] = [1, 2, 3];
//左右两边形式必须统一
let [d, [e, f], g] = [1, [2, 3], 4];
//默认值
let [h = 1] = []
h //1
let {hello = 'ES6'} = {}
hello //ES6
//使用圆括号
let es6;
{es6} ={es6:'一起学习'}; //报错
//解决错误
let ES6;
({ES6} = {ES6:'一起学习'});
五、扩展运算符和rest运算符
扩展运算符 就是三个点...
//数组
const a = [1, 2]
const b = [...a, 3, 4]
console.log(b) //[1, 2, 3, 4]
//对象
const c = {first: 1, second: 2}
const d = {...c, third: 3}
console.log(d) //{first: 1, second: 2, third: 3}
rest运算符 数组或者对象除了某几项的其他项
//数组
const a = [1, 2,3,4,5]
const [b,...num]=a
console.log(num) //[2, 3, 4, 5]
//对象
const c = {first: 1, second: 2,third:3}
const {first, ...rest}=c
console.log(rest) //{second: 2, third: 3}
对于Object,当然如果有重复的属性名,后者会覆盖前者
const first = {
a: 1,
b: 2,
c: 5,
}
const second = {
c: 3,
d: 4
}
const total = { ...first, ...second }
console.log(total) // { a: 1, b: 2, c: 3, d: 4 }
六、数组的知识
1、Array.of()
方法:把一组值转换成数组
let arr1 =Array.of(1,2,3);
let arr2 =Array.of('hello','every','你好');
console.log(arr1); //[1, 2, 3]
console.log(arr2); //["hello", "every", "你好"]
2、Array.from()
方法: 用于将两类对象转为真正的数组
let arr = {
'0': 'a',
'1': 'b',
'2': 'c',
length: 3
};
console.log(Array.from(arr)) //["a", "b", "c"]
3、find() 和 findIndex()
实例方法
find方法,找出第一个符合条件的数组成员
findIndex方法,返回第一个符合条件的数组成员的位置
需要传入一个匿名函数,函数传入三个参数
value
当前查找的值
index
当前查找的数组索引
arr
当前数组
let arr =['a','b','c']
console.log(arr.find(function(value,index,arr){
return value>'b'
})) //c 如果找不到显示 undefined
console.log(arr.findIndex(function(value,index,arr){
return value>'b'
})) //2 如果找不到显示 -1
4、fill( )
实例方法 :使用给定的值填充到数组 ,接收三个参数(填充的变量,开始填充的位置,填充到的位置)
let arr =['a','b','c'];
console.log(arr.fill('d',1,3)) ;//["a", "d", "d"]
console.log(arr.fill('e',1,5)) ;//["a", "e", "e"]
5、数组循环
for…of
循环
let arr = ['a', 'b', 'c'];
for (let item of arr) {
console.log(item)
}
//a b c
/**
*获取数组的索引
* */
for (let index of arr.keys()) {
console.log(index)
}
//0 1 2
/**
*获取数组的索引和内容
* */
for (let [index, val] of arr.entries()) {
console.log(`${index}:${val}`)
}
//0:1 1:b 2:c
forEach
map
filter
some
every
let arr = ['a', 'b', 'c'];
arr.forEach(function (val, index) {
console.log(val, index)
})
//a 0 b 1 c 2
/**
*对数组进行运算
* */
var a=arr.map(function (value,index,arr) {
return `新增${index+1}`
})
console.log(a) //["新增1", "新增2", "新增3"]
/**
*把条件符合的项目组成一个新的数组
* */
var b = arr.filter(function (item, index, arr) {
return index > 0
})
console.log(b) //["b", "c"]
/**
*数组中的元素部分满足指定条件返回true
* */
var c = arr.some(function (item, index, arr) {
return index > 1
})
console.log(c) //true
/**
*数组中的元素全部满足条件返回true否则false
* */
var d = arr.every(function (item, index, arr) {
return index > 1
})
console.log(d) //false
七、箭头函数
箭头函数 就是函数的快捷写法 =>
//ES5
function add1(a, b) {
return a + b;
}
console.log(add1(1, 2)); //3
//ES6 增加了默认值
let add2 = (a, b = 2) => a + b
console.log(add2(1)) //3
//方法体内如果是两句话,用 {}包起来
let add3 = (a, b = 2) => {
a = a + 1;
return a + b;
}
console.log(add3(1)) //4
可以把JSON格式数据当作参数
let json = {
a: 1,
b: 2
}
let add = ({a, b = 3}) => a + b
console.log(add(json)); //3
通过省略冒号与 function
关键字,将语法变得更简洁
//ES5
var people = {
name: 'every',
getName: function() {
console.log(this.name)
}
}
//ES6
const people = {
name: 'every',
getName () {
console.log(this.name)
}
}
八、Set
Set数据结构类似数组,但是成员没有重复值。
let setArr = new Set(['a', 'b', 'c', 'c']);
console.log(setArr); //{"a", "b", "c"}
数据操作
let setArr = new Set(['a', 'b', 'c', 'c']);
// 增加 add
setArr.add('d');
console.log(setArr); //{"a", "b", "c", "d"}
// 查找 has
console.log(setArr.has('b')); //true
// 删除 delete clear
setArr.delete('a');
console.log(setArr); //{"b", "c", "d"}
setArr.clear();
console.log(setArr); //{}
遍历操作
keys()
返回键名values()
返回键值entries()
返回键值对forEach()
使用回调函数遍历成员
let setArr = new Set(['a', 'b', 'c', 'c']);
for (let item of setArr.keys()) {
console.log(item);
}
//a b c
for (let item of setArr.values()) {
console.log(item);
}
//a b c
for (let item of setArr.entries()) {
console.log(item);
}
//["a","a"] ["b","b"] ["c","c"]
setArr.forEach((values, key) => console.log(`${key}:${values}`))
//a:a b:b c:c
由于 Set 结构没有键名,只有键值(或者说键名和键值是同一个值),所以keys方法和values方法是一样的,entries键值对是一样的。
九、Map
Map数据结构类似对象,其键值可以是任何类型 [值-值]
数据操作
let json = {
name: 'every',
sex: 'man'
}
var map = new Map();
//加值 set
map.set('a', json);
map.set(json, 'a');
console.log(map); //{"a" => {…}, {…} => "a"}
//查找 has
console.log(map.has('a')); //true
console.log(map.has(json)); //true
//取值 get
console.log(map.get(json)); //a
console.log(map.get('a')); //{name: "every", sex: "man"}
//size 属性
console.log(map.size); //2
//删除 delete
console.log(map.delete('a')); //true
console.log(map); //{{…} => "a"}
//清除 clear
console.log(map.clear()); //undefined
遍历操作 和Set
遍历操作差不多
十、Promise
Promise
可以将异步操作同步表达出来
特点:对象的状态不受外界影响; 状态一旦改变就不会在变;
const promise = new Promise(function(resolve, reject) {
// ... some code
if (/* 异步操作成功 */){
resolve(value);
} else {
reject(error);
}
});
resolve
函数的作用,将Promise
对象的状态从未完成
变成成功
(pending
变成resoled
)
reject
函数的作用,将Promise
对象的状态从未完成
变成失败
(pending
变成rejected
)
Promise
实例生成后,可以用then
方法分别指定resolved
状态和``rejected`状态的回调函数
promise.then(function(value) {
// success
}, function(error) {
// failure
});
then
方法可以接受两个回调函数作为参数。第一个回调函数是Promise
对象的状态变为resolved
时调用,第二个回调函数是Promise
对象的状态变为rejected
时调用。其中,第二个函数是可选的,不一定要提供。这两个函数都接受Promise
对象传出的值作为参数。
let promise = new Promise((resolve, reject)=> {
console.log('Promise');
resolve();
});
promise.then(() => {
console.log('resolved.');
},() => {
console.log('rejected.');
});
十一、class
基本使用
class Num {
add1(val) {
console.log(val + 1);
}
add2(val) {
console.log(val + 2)
}
}
let num =new Num();
num.add1(1);
num.add2(1);
类的传参 constructor
class Num {
add1(val) {
console.log(val + 1);
}
add2(val) {
console.log(val + 2)
}
constructor(a, b) {
this.a = a;
this.b = b;
}
add(){
console.log(this.a+this.b)
}
}
let num = new Num(1,2);
num.add();
类的继承 extends
class Num {
add1(val) {
console.log(val + 1);
}
add2(val) {
console.log(val + 2)
}
constructor(a, b) {
this.a = a;
this.b = b;
}
add() {
console.log(this.a + this.b)
}
}
class Second extends Num {
}
let second = new Second();
second.add1(1);
十二、export 和 import
export
就是模块的输出
import
就是模块的引入
const people = {
name: 'every',
sex: 'man'
}
//全部导入
import people from './people'
//as 给模块取一个别的名称
import * as example from "./people"
//导入部分
import {name, sex} from './people'
// moren导出, 有且只有一个默认
export default App
1.当用export default people导出时,就用 import people 导入(不带大括号)
2.一个文件里,有且只能有一个export default。但可以有多个export。
3.当用export name 时,就用import { name }导入(记得带上大括号)
4.当一个文件里,既有一个export default people, 又有多个export name 或者 export age时,导入就用 import people, { name, sex }
5.当一个文件里出现n多个 export 导出很多模块,导入时除了一个一个导入,也可以用import * as example