ES6
Let和Const
let:相当于es6之前的var
const:定义常量
let:
1.没有预解析,不存在变量提升(在代码块内,只要let定义变量,在之前使用,都会报错)
2.同一个作用域不能重复定义变量
3.for循环里面是
应用:选项卡
var aInput = document.querySelectorAll('input');
for(let i = 0;i<aInput.length;i++){
aInput[i].onclick = function(){
alert(i);
}
}
const:(和let相同)
1.const定义变量不能修改(但是在定义数组之后可以push,这是因为对象是引用,如果想不可以push,用Object.freeze()
2.const定义完变量,必须有值,不能后赋值,不能修改
解构赋值
用于数据交互
let [a,b,c]=[1,2,3]
let [a,b,c]=[1,[2,3]]
注意:左右格式保持一致
let json={name:’aa’,age:3,job:’teacher’};
{name,age,job}=json;
let {name:n,age:g,job:j}=json;
解构的时候可以给默认值
let [a,b,c=’暂无数据’] = [‘aa’,’bb’,]
注意解构时的块级作用域报错,解决:通过加一个括号将赋值语句包裹
let a;
({a}={a:’apple,b:’banana’});
应用:交换两个数的位置
let a = 12;
let b = 5;
[a,b] = [b,a]
应用:在import包的时候
Import {a,b,c} from ‘./asset/….’
应用:函数参数默认值
function show({a=’默认a’,b=’默认b’}={}){
console.log(a,b)
}
show()
字符串模板
let a = ‘张三’;
let b=18;
let c=`${a}今年${b}岁`
优点:可以换行
字符串新增
字符串查找
Str.indexOf(要找的东西) 返回索引(位置),没找到返回-1
Str.includes(要找的东西)返回true/false
应用:判断浏览器
If(navigator.userAgent.includes(‘Chrome‘)){alert(‘是chrome’}’
字符串是否以xxx开头
Str.startswith(要检测的东西)
应用:检测地址
字符串是否以xxx结尾
Str.endswith(要检测的东西)
应用:检测后缀
字符串重复
Str.repeat(重复次数)
字符串填充
向前填充
Str.padStart(填充后整个字符串长度,填充内容)
向后填充
Str.padEnd(填充后整个字符串长度,填充内容)
Ps:可以通过.length相加来确定字符串长度
函数
函数默认参数
之前:
function show(a,b){
a=a||'is a';
b=b||'is b';
console.log(a,b);
}
show('aaa','bbb')
show('aaa')
1.函数默认参数
function show({x=0,y=0}={}){
console.log(x,y);
}
show();
2.函数参数默认已经定义了,不能再使用let,const声明
function show(a=18){
let a = 12; //会报错
}
扩展运算符
const arr = ['apple','banana','orange']
console.log(arr); //输出['apple','banana','orange']
console.log(...arr); //输出apple banana orange
function show(a){
console.log(a); //输出 1
}
show(1,2,3,4,5)
function show(...a){
console.log(a); //输出 [1,2,3,4,5]
}
show(1,2,3,4,5)
排序:
function show(){
let a = Array.prototype.slice.call(arguments).sort();
return a;
}
console.log(show(1,5,2,6,3))
//es6中
function show(...a){
return a.sort();
}
console.log(show(1,5,2,6,3))
剩余参数
...必须放在末尾
function show(a,b,...c){
console.log(a,b); //1 2
console.log(c); //[3,4,5]
}
show(1,2,3,4,5);
箭头函数
let show = ()=>1;
//相当于
function show(){
return 1;
}
() => return 的东西
() => { 语句;return的东西}
ps:注意:
1.this的指向问题,定义函数所在的对象,不再是运行时所在的对象
2.箭头函数中没有arguments,用...
3.箭头函数不能当构造函数
数组
arr.forEach() 代替for,没有返回值
arr.forEach(function(val,index,arr){ //val为数组中的每一项,index为下标,arr为数组本身
console.log(val,index,arr);
});
arr.map() 主要用于做数据交互,“映射”,一般配合return使用,返回一个新的数组,否则相当于forEach()
应用:整理后台返回的数据结构
arr.filter() 主要用于过滤一些不合格“元素”,一般配合return使用
arr.some() 主要用于查找,返回true/false,数组中某个元素符合条件返回true
arr.every() 主要用于查找,返回true/false,数组中所有元素符合条件返回true
以上方法接收两个参数(循环的回调函数,this指向),若循环的回调函数为箭头函数,则第二个参数失效
arr.reduce() 主要用于求数组的和、阶乘,从左向右
let arr = [1,2,3,4,5,6,7,8,9,19]
let res = arr.reduce((pre,cur,index,ar)=>{
return pre+cur;
});
//pre是前n向的和,cur是当前项,类似于递归
arr.reduceRight() 主要用于求数组的和、阶乘,从右向左
新增数组for循环
for...of..
arr.keys() 数组下标
arr.entries() 数组某一项
let arr=['apple','banana','orange','tomato']
for(let val of arr){
console.log(val);
}
//apple
//banana
//orange
//tomato
for(let index of arr.keys()){
console.log(index);
}
//0
//1
//2
//3
for(let item of arr.entries()){\
console.log(item);
}
//[0,'apple']
//[1,'banana']
//[2,'orange']
//[3,'tomato']
for(let [key,val] of arr.entries()){
console.log(key,val);
}
//0 'apple'
//1 banana
//2 orange
//3 tomato
for(let val of arr.values()){
console.log(val)
}
//报错,因为这里本身就用的是values
Array.form:把类数组(获取一组元素、arguments...)对象转为数组
function show(){
let arr = Array.form(arguments);
console.log(arr)
};
show(1,2,3,4,5);
//[1,2,3,4,5]
应用:定义length将对象转为数组
let json={
0:'apple',
1:'banana',
2:'orange',
length:2
}
let arr = Array.form(json);
console.log(arr); //['apple','banana']
Array.of:把一组值转为数组
let arr = Array.of('apple','banana','orange');
console.lof(arr); //['apple','banana','orange']
arr.find()方法:找出第一个符合要求的数组成员,如果没有找到,返回undefined
let arr = [23,90.54,110,44,101]
let res = arr.find((val,index,arr)=>{
return val>100;
}
console.log(res) //110
arr.findIndex():找出第一个符合要求数组成员的位置,如果没有找到,返回-1
arr.fill() :用于数组的填充
arr.fill(填充的东西,开始位置,结束位置) 位置从0开始
arr.includes():判断数组中是否包含某个成员,包含返回true,不包含返回false
对象
Object.is():比较两个对象是否相等
console.log(NaN == NaN); //false
console.log(Number.isNaN(NaN)); //true;
let b = Object.is(NaN,NaN);
console.log(b) //true
console.log(+0 == -0) //true;
console.log(Object.is(+0,-0)); //false;
Object.assign():用来合并对象
let json1 = {a:1};
let json2 = {b:2,a:2};
let json3 = {c:4};
let obj = Object.assign({},json1,json2,json3);
consloe.log(obj); //{a:2,b:2,c:4} 后面的会覆盖前面的
应用:1.复制一个对象(数组)2.合并参数
Object.keys()
let json = {
a:1,
b:2,
c:3,
}
for(let key of Object.keys(json)){
console.log(key);
}
Object.entries()
Object.values()
对象的扩展运算符
let {x,y,...z} = {x:1,y:2,a:3,b:4}
console.log(x,y,z); //1 2 {a:3,b:4}
Promise:解决异步回调问题
传统方式大部分用回调函数
let promise = new Promise(function(resolve,reject){
//resolve,成功
//reject,失败
});
promise.then(res=>{
},err=>{
})
promise.catch(err=>{ //reject,发生错误
console.log(err);
})
Promise.resolve('aa'):将现有的东西,转成一个promise对象,resolve状态,成功状态
等价于:
new Promise(resolve=>{
resolve('aaa');
});
Promise.reject('aaa'):将现有的东西,转成一个promise对象,reject状态,失败状态
等价于:
new Promise((resolve,reject)=>{
reject('aaa');
});
Promise.all([p1,p2,p3]):把Promise打包,返回值在一个数组中,打包完依旧是promise对象
必须确保所有的promise对象都是resolve状态,都是成功状态
Promise.race([p1,p2,p3]):把Promise打包,返回值在一个数组中,打包完依旧是promise对象
只要有一个promise对象是resolve状态,就是成功状态
模块化
1.定义 export
2.使用 import
注意:
1.import可以是相对路径,也可以是绝对路径
2.import模块无论引入多少次,只会导入一次
3.import './xxx/xx.js' 相当于引入文件
4.有提升效果,import会自动提升到顶部首先执行
5.导出模块内容,如果里面有定时器修改,外面也会改动
import()类似node里面require,可以动态引入,默认import语法不能写到if之类里面
优点:1.按需加载 2.可以写在if中 3.路径也可以动态
function config(sign:number){
switch(sign){
case 1:
return './xx/x.js';
break;
case 2:
return '.xxx/xx.js';
break;
}
}
import(config(1)).then(res=>{
...
});
Promise.all([
import('./xx/x.js');
import('./xxx/xx.js');
]).then(([xx,xxx])=>{
console.log(xx);
console.log(xxx);
});
类
ES6中变形:
class Person{
constructor(){
this.name='aaa';
}
showName(){
}
}
注意:在ES6里面class没有提升,在ES5中默认函数提升
class中取值函数getter,存值函数setter
class Person{
constructor(){}
get aaa(){
return `aaa的属性`;
}
set aaa(val){
console.log(`设置aaa属性,值为:${val}`);
}
}
let p1 = new Person();
p1.aaa='123'; //设置aaa属性,值为:123
console.log(p1.aaa); //aaa的属性
数据类型
symbol
定义:
let syml = Symbol('aaa')
注意:
1.Symbol不能new
2.Symbol()返回值是一个唯一值
3.Symbol是一个单独的数据类型,是symbol基本类型
4.如果symbol作为key,用在for in循环中,遍历不出来
generator函数 生成器
解决异步、深度嵌套问题,但现在一般都用async
语法:
function * show(){}
function* show(){}
function *show(){}
function * gen(){
yield 'hello';
yield 'world';
}
let g = gen();
console.log(g.next()) //{value:'hello',done:false}
console.log(g.next()) //{value:'wordl',done:true}
console.log(g.next()) //{value:undefined,done:true}
可以配合for...of、解构赋值、扩展运算符、Array.from使用
应用:结合axios请求数据,得到数据后再根据得到的value进行下一步
总结:关于异步的解决方案:
1.回调函数 2.时间监听 3.发布/订阅 4.Promise对象 5.async/await
async、await
async function fn(){ //表示异步,这个函数里面有异步任务
let result = await xxx //表示后面结果需要等待
}
async特点:
1.await只能放到async函数中
2.相比genrator语义化更强
3.await后面可以是promise对象,也可以数字、字符串、布尔
4.async函数返回是一个promise对象
5.只要await语句后面promise状态变成reject,那么整个async函数会中断执行
解决async函数中抛出错误影响后面代码:
1.通过try{}catch(){}
2.通过promise本身的catch
当请求之间没有关系的时候用Promise.all([])
Set和WeakSet
set数据结构:类似数组,但是数组中不能有重复值
用法:new Set(array)
.add()方法:往set数组中添加一项
.delete('x')方法:删除set数组中的x
.has('x')方法:判断set数组中是否有x
.size()方法:判断set数组有几项
.clear()方法:将set数组中所有项清除
set循环
1.for(let item of setArr){console.log(item);} //默认是value()
2.for(let item of setArr.keys()){console.log(item);} //输出value
3.for(let item of setArr.values(){console.log(item);} //输出value
4.for(let [k,v] of setArr.entries()){console.log(item);} //输出key value
相当于setArr.forEach((value,index)=>{console.log(value,index);}
应用:数组去重
let arr = [1,2,3,3,4,4,4,5]
let newArr = [...new Set(arr)]
set数据结构变成数组:用扩展运算符 arr = new Set([...set])
WeakSet
用法:存储json对象
注意:初始向WeakSet中添加对象是不成功的,用.add()方法添加。WeakSet方法没有size()方法和clear()方法
Map
类似json,但是json的键只能是字符串,Map的键可以是任意类型
用法:let map = new Map()
map.set(key,value) 设置一个值
map.get(key) 获取一个值
map.delete(key) 删除一项
map.has(key) 判断有没有
map.clear() 清空
map循环
1.for(let [k,v]of map){console.log(item);} //默认是entries
2.for(let keyof map.keys()){console.log(item);} //输出value
3.for(let keyof map.values(){console.log(item);} //输出value
4.for(let [k,v] of map.entries()){console.log(item);} //输出key value
WeakMap
key只能是对象
总结:
Set里面是数组,不重复,没有key,没有get方法
Map对json功能增强,key可以是任意类型值
数字(数值)变化
二进制(binary):let a = 0b10 //2
八进制(octal):let a = 0o666 //438
十六进制:#ccc
Number.isNaN(NaN) //true 判断是否是NaN
Number.isFinite() //判断是否是数字
Number.isInteger() //判断是否是整数
Number.parseInt()
Number.parseFloat()
安全整数:[-(2^53-1),(2^53-1)]
Number.isSafeInteger() //判断是否是安全整数
Number.MAX_SAFE_INTEGER 最大安全整数
Number.MIN_SAFE_INTEGER 最小安全整数
Math
Math.abs() 取绝对值
Math.sqrt() 得到平方根
Math.sin() 计算正弦
Math.trunc() 截取(保留整数部分)
Math.sign() 判断是正数还是负数还是0 正数返回1 负数返回-1 0返回0 -0返回-0
Math.cbrt() 得到立方根
命名捕获
语法:(?<名字>)
let str = '2021-01-01'
let reg = /(?<year>\d(4))-(?<month>\d(2))-(?<day>\d(2))/
let (year,month,day) = str.match(reg).groups;
console.log(year,month,day) //2021 01 01
反向引用命名捕获
语法:\k<名字>
let reg = /^(?<Strive>welcome)-\k<Strive>$/ 匹配'welcome-welcome'
let reg = /^(?<Strive>welcome)-\k<Strive>-\1$/ 匹配‘welcome-welcome-welcom’
应用:替换字符串
语法:$<名字>
let reg = /(?<year>\d(4))-(?<month>\d(2))-(?<day>\d(2))/
str = str.replace(reg,'$<day>/$<month>/$<year>')
dotAll模式
/ /s
之前'.'在正则里表示匹配任意东西,但是不包括\n
加了s之后 在//中间发现点时,可以匹配任意,包括\n
标签函数
定义:function fn(){}
使用:fn`aaa`
Proxy代理
作用:vue拦截,预警、上报、扩展功能、统计、增强对象等
是设计模式一种,代理模式
语法:
new Proxy(target,handler);
let obj = new Proxy(被代理的对象,对代理的对象所做的操作)
handler中的方法:
set() 设置代理的时候调用
get() 获取代理的时候调用
deleteProperty() 删除
has() 判断是否存在某个元素
apply 调用函数处理
let obj={
name:'ttt'
};
let newObj = new Proxy(obj,{
get(target,property){
console.log(target,property);
}
});
console.log(newObj.aaa) //输出{name:'ttt'} aaa
//aaa为参数中的property target为obj
应用:访问一个对象身上属性,默认不存在的时候给undefined,如果不存在给错误提示
let obj={
name:'ttt'
};
let newObj = new Proxy(obj,{
get(target,property){
if(property in target){
return target[property];
}else{
throw new ReferenceError(`${property}属性不在此对象上`);
}
}
});
console.log(newObj.name)
console.log(newObj.age)
Reflect反射
通过Reflect对象直接拿到语言内部的东西