ES6的一些小总结

一、let const

let 相当于之前的var。
const 常量,定义好后不可以改变。

let注意:
1.没有预解析,不存在变量提升
在代码块内,只要let定义变量,在之前使用,都
是错误的。
2.在同一个作用域里面,不能重复定义变量。
3.for循环,for循环里面是父级作用域,里面又是一
个。

const:特性盒let是一样的。
1. const定义变量不能修改
2. const定义完变量,必须有值,不能后赋值,不能修改。
3.const arr = object.freeze(['apple']);这种方式为冻结方式,arr.push(‘orange’)会报错,是不允许修改的。
4.const config = {
hot:
username:
}
config.hot = 11//外界可以通过这个可以修改

{
块级作用域
}


二、解构解析

*非常有用,特别在做数据交互 ajax

let [a,b,c] = [12,5,6];


注意:左右两边,结构格式要保持一致

let json = {
name : 'Hansen',
age : 19,
job : '好人'
};
let {name,age,job} = json;
console.log(name,age,job);

let{name:n,age:g,job:a} = json;



解构时候可以给默认值:
let[a,b,c="默认值"] = ['aaa','bbb']

一些案例

//对象赋值
let json = {
    name : 'Hansen',
    age : 19,
    job : '好人'
};
let {name,age,job} = json;
console.log(name,age,job);

 

//交换两个数字
  let a = 5;
  let b = 6;
  [a,b] = [b,a];
  console.log('a='+a+',b='+b);

 

//另一种赋值
function getPos() {
    return{
        left:22,
        top:220
    }
}
let {left,top:t} = getPos();
console.log(left,t);//top和t是相同的
//给默认值
   function  show({a,b='默认'}) {
      console.log(a,b);
      }
     show({
         a:1
         });

 


三、字符串模板

优点:可以随意换行
`${变量名字}`
 

let name = 'Hansen';
let age = 18;
let str = `我叫${name},年龄是${age}岁`;//其中``为拼接字符,${name}为变量
console.log(str);


`这个符号为英文模式下1左边这个符号

关于字符串一些东西
字符串的查找:
str.indexOf(要找的东西),返回索引(位置),没有找到返回-1
str.includes(要找的东西),返回值true/false

检测以谁开头 如http
str.startsWith("检测东西")

检测以谁结尾 如.png .html
str.endsWith("检测东西")

重复字符串:
str.repeat(次数);

填充字符串:
str.padStart(填充后整个字符串的长度,填充的东西)//往前填充
str.pdEnd(填充后整个字符串的长度,填充的东西)//往后填充


四、函数默认参数、箭头函数、剩余参数

箭头函数
//用war定义一个全局变量,属于window 与 let ,const是不同的

()=>return 东西
(参数)=>{
语句
return
}
注意:
1.this问题,定义函数所在的对象,不再是运行时所在的对象
2.箭头函数里面没有arguments,用剩余参数'...'
3.构造函数,箭头函数不能当作箭头函数

函数变化:
1.函数默认参数

function show({x=0,y=0}={}) {
console.log(x,y);
}
show();//0 0


2.函数参数默认已经定义了,不能再使用let,const在函数内定义声明。

function show(a=10){
let a = 101;
console.log(a);
}
show();//Uncaught SyntaxError: Identifier 'a' has already been declared



3.扩展运算符 也可以reset运算符的作用 就是 三个点 ... ,能展开数组,是一个扩展,也可以重置,也是剩余运算符

function show(...[a,b,c]) {
console.log(a,b,c);
}
show(2,3,4);//2 3 4

 

function show(a,b,...c) {
    console.log(a,b,c);
}
   show(2,3,4,5,6,7,8,9);//2 3 [4, 5, 6, 7, 8, 9]

五、循环的数组

数组:
es5新增一些东西
循环 :
1.for
for(let i=0;i<arr.length;i++)
2.while
arr.foreach()//代替普通函数

let arr = ['菠萝','雪梨','香蕉','苹果','桃子'];
    arr.forEach(function (val,index,arr) {
           console.log(val,index);
          });
//菠萝 0 雪梨 1 香蕉 2 苹果 3 桃子 4

 

let arr = ['菠萝','雪梨','香蕉','苹果','桃子'];
arr.forEach(function (val,index,arr) {
    console.log(this,val,index,arr);
}.bind(123));//this指向的是123,其他的与上段代码一样



arr.map()//非常有用,做数据交互“映射”
// 正常情况下,需要配合return,
返回是一个新的数组
//若是没有人return,相当于forEach
注意:平时只要用map,一定是要有return的可以做重新整理数据结构用[{title:'aaa'}]->[{t:'aaaaaa'}]//详情见代码

let arr = [
    {title:'aaadf',read:100,hot:true},
    {title:'vvvvv',read:110,hot:true},
    {title:'wwwww',read:400,hot:true},
    {title:'aaazc',read:102,hot:true},
    {title:'fffff',read:103,hot:true},
    ];
let newArr = arr.map((item,index,arr)=>{
    let json = {};
    json.t1 = `(*^_^*)${item.title}-----`;
    json.r = item.read + 200;
    json.hot = item.hot == true && '你真棒了';
    return json;
    });

console.log(newArr);
       /*       0: {t1: "(*^_^*)aaadf-----", r: 300, hot: "你真棒了"}
        1: {t1: "(*^_^*)vvvvv-----", r: 310, hot: "你真棒了"}
        2: {t1: "(*^_^*)wwwww-----", r: 600, hot: "你真棒了"}
        3: {t1: "(*^_^*)aaazc-----", r: 302, hot: "你真棒了"}
        4: {t1: "(*^_^*)fffff-----", r: 303, hot: "你真棒了"}*/


arr.filter();//过滤,过滤一些不合格的“元素”,如果回调函数返回true(看return的是什么条件),就留下来

let arr = [
 {title:'aaadf',read:100,hot:true},
 {title:'vvvvv',read:110,hot:true},
 {title:'wwwww',read:400,hot:false},
 {title:'aaazc',read:102,hot:true},
 {title:'fffff',read:103,hot:false},
 ];
 let newArr = arr.filter((item,index,arr)=>{
   return item.hot==false;
 });

 console.log(newArr);
/*
0: {title: "wwwww", read: 400, hot: false}
1: {title: "fffff", read: 103, hot: false}
*/


arr.some();//类似查找,数组里面某一个元素符合条件,返回true
arr.every();//数组里面所有的元素都要符合条件才能返回true

其实上面他们可以接收两个参数:
arr.forEach/map/..every...(循环回调函数,this指向谁)
arr.reduce();//从左往右
//求数组的和/阶乘

let arr = [2,3,4];
let res = arr.reduce((prev,cur,index,arr)=>{
return prev*cur;//2*3*4=16
//四个参数,prev是当前数组第一个,cur为下一个数组元素
console.log(res);


附加:Math.pow()与**的效果是一个样的 就是幂运算 为8

arr.reduceRight();//从右往左
===================================
for...of...循环
arr.keys() 数组下标
arr.entries() 数组某一项
for(let val of arr){
console.log(val);
}

 

扩展运算符
Array.from:
作用:类数组(获取一组元素、arguments...)对象转成数组。

let aLi = document.querySelectorAll("ul li");
let arrLi = Array.from(aLi);//转化成类数组
console.log(arrLi);


个人观点:只要具备length这个特点,就是靠谱的

let json = {
0:'apple',
1:'banana',
2:'orange',
length:3
};
let arr = Array.from(json);
console.log(arr);//(3) ["apple", "banana", "orange"]


arr.find():查找,找出第一个符合条件的数组成员,如果没有找到,返回underfunded

let arr = [2,33,44,55,66];
let newArr = arr.find((val,index,arr)=>{
return val > 50;
})
console.log(newArr);


arr.findIndex:找的是位置,找到则返回位置,没有找到返回-1,
arr.fill(填充的东西,开始位置,结束位置) //填充

let arr = new Array(10);
arr.fill('1');
console.log(arr);//(5) ["1", "1", "1", "1", "1"]


arr.includes:有没有包含此项

arr.indexOf();
arr.includes();
let arr = ['patch','apple','watermelon','banana'];
let newArr = arr.indexOf('apple');
let newArr2 = arr.includes('apple');
console.log(`${newArr}-----${newArr2}`);//1-----true

六、对象新增

对象
json
对象简介语法(相当有用)

let json = {
a:1,
b:2,
showA:function () {
return this.a;
},
showB:function () {
return this.b;
}
};

let a = 'hello';
let b = 26;
let json = {
a,
b,
showA(){//个人建议,一定注意不要用箭头函数
return this.a;
},
showB(){
return this.a;
}
};

//console.log(json.showA());

 

Object.is();//用来比较两个值是否相等
Object.is(+0,-0);//false
Object.is(NaN,NaN);


Object.assign() 用来合并对象的
let 新的对象 = Object.assign(目标对象,source1,source2....);
function ajax(options){
let defaults={
type:'get',
header:
data:{}
...
}
let json = Object.assign({},defaults,options);
.......
}
用途:
1.复制一个对象
2.合并参数
====================================
ES2017引入
Object.keys();
Object.entries();
Object.values();

 

let json = {
    a:1,
    b:2,
    c:3
};
for (var key of keys(json)) {
    console.log(key);//a b c
}
for (let value of values(json)) {
    console.log(value);//1 2 3
}

for (let item of entries(json)) {
    console.log(item);
    /*
    * ["a",1]
    * ["b",2]
    * ["c",3]
    * */
}
for (let [key,val] of entries(json)) {
    console.log(key,val);
}
/*
* a 1
* b 2
* c 3
* */

七、Promise

Promise
作用:解决异步回调的问题
传统方式,大部分用回调函数,事件
//语法
let promise = new Promise(function (resolve,reject) {
//resolve 成功调用
//reject 失败调用
})

下面是实际代码

let a = 1;
let promise = new Promise(function (resolve,reject) {
if(a == 10){
resolve("成功");
}else {
reject("失败的鸟儿")
}
});


//promise.then(success,fail);接受2个参数,成功与失败

new Promise().then(res=>{}).catch(err=>{});

promise.then(res=>{
consloe.log(res);
},err=>{
console.log(err);
});

Promise.resolve('aa'):将现有的东西,转化一个promise对象,resolve状态,成功状态。等价于:
          new Promise(resolve=>{
                 resolve("aaa");
                     });
Promise.reject("aaa") 将现有的东西,转成一个promise对象,reject状态,失败状态。等价于:
         new Promise((resolve,reject)=>{
                reject("aaa");
                     });


八、模块化


那么ES6模块化怎么用呢
注意:

1.要放在服务器环境才可以使用
2.import './modules/1.js';

a).如何定义模块?
export 东西
export const a = 12;
export{
a as aaa,
b as banana
}
export default 12;
b).如何使用?
import
import './modules/1.js';
import {a,b,c} from './modules/2.js'
import * as modTwo from './modules/2.js'
import a from './modules/2.js' //只有default出来的不用花阔号

使用模块:
<script type="module"></script>

import:
a).import可以是相对路径,也可以是绝对路径
import "https://code.jquery.com/jquery-3.3.1.js"
b).import模块指挥引入一次,无论你导入多少次
c)import './modules/1.js';如果这么用,相等于引入文件
d)import 又提升的效果,import会自动提升到顶部,首先执行。
e).到出去模块内容,如果里面有定时器更改,外面也会改动,不像Comon规范缓存。

import() 类似node里面require,可以动态引入的,,而且他是有返回值的,是个promise对象,而默认import语法不能写到if之类里面,因为他是静态的,必须先引入再调用。
import('./modules/1.js').then({}res=>{
console.log(res.a + res.b);
});
优点:
1.按需加载
2.可以写到if中
3.路径也是可以动态的


九、类和继承

Person.prototype.showName
Es5之前

function Person(name,age) {
this.name = name;
this.age = age;
}
Person.prototype.showName = function () {
return `名字为${this.name}`;
};
Person.prototype.showAge = function () {
return `年龄为${this.age}`;
}
let p1 = new Person('Hansnen',18);
console.log(p1.showName());
console.log(p1.showAge());



Es6变形

class Person{
constructor(name,age){//构造方法(函数),调用new,自动执行
//console.log(`构造函数执行了,${name},${age}`);
this.name = name;
this.age = age;
}
showName(){
return `名字为${this.name}`;
}
showAge(){
return `年龄为${this.age}`;
}
}
let p1 = new Person('Hansen',18);
console.log(p1.showName()+'--'+p1.showAge());

 

let a = 'Hanens';
let b = 'method';
class Person{
[a+b](){
return 'Hello';
}

}
let p1 = new Person();
console.log(p1[a+b]);

//或者
let aaa ='aaa';
let bbb ='ddd';

let json = {
[aaa+bbb]:'我是个好人';
}


注意:
1.ES6是没有提升功能的,再ES5,用函数模拟是可以的,默认函数提升.
2.ES6里面this比之前是轻松多了

矫正this:
1.fn.call(this指向谁,args1,args2...)
2.fn.apply(this指向谁,[args1,args2]);
3.fn.bind()


class里面取值函数(getter),存值函数(setter)?

class Person{
get aaa(){
return 'aaa的属性';
}
set aaa(val){
console.log(`设置aaa属性,值为:${val}`);//这里为设置属性
}

}
let p1 = new Person();
p1.aaa = '1223';
console.log(p1.aaa);//用get去获取属性


====================================
静态方法:就是类身上的方法
 

class Person{
showName(){
return '这是showName方法';
}
static aaa(){
return '这是静态方法';
}

}
let p1 = new Person();

console.log(p1.showName());
console.log(Person.aaa());



继承:

现在:extends
//父类

class Person{
constructor(name){
this.name = name;

}
showName(){
console.log('父类的showName');
return `名字为:${this.name}`;
}
}


//子类

class Student extends Person{
constructor(name,skill){
/*如果直接是constructor(),就会覆盖父类的构造函数,会报错,所以要在参数中加上父类构造函数中有的
参数,然后加上子类特有的参数,然后super()下,super里面参数为父类的*/
super(name);
this.skill = skill;

}
showName(){
super.showName();//super让父级的方法先执行

//todo 做子集的事情
console.log('这是子集的showName');

}
showSkill(){
return `哥们的那个技能为:${this.skill}`;

}

}
//调用
let stu1 = new Student('Strict','上课');
console.log(stu1.skill);
console.log(stu1.showName());

十、Set和WeakSet

数据结构

set数据结构
类似数组,但是里面不能有重复的重复值
set用法:
new Set(['a','b']);
setArr.add('a');往setArr里面添加一项
setArr.delete('a');往setArr里面删除一项
setArr.has('a');判断setArr里面有没有此值
setArr.size //看里面有多少个,相当于长度length
setArr.clear();//清空所有的
=====================================
for...of...
循环:
a).for(let item of setArr){//默认是values();
console.log(item);
}
b).for(let item of setArr.keys()){consloe.log(item);}
c).for(let item of setArr.values()){}
d).for([k,v] of setArr.entries()){}
e).setArr.forEach((value,index)=>{
console.log(value,index);
});
d==e
==========================
链式增加
let setArr = new Set().add('a').add('b').add('c');
数组去重
let arr = [1,2,3,1];
let newArr = [...new Set(arr)];
console.log(newArr);
set数据结构变成数组:
[...set]
然后set变成数组之后,一些有关于数组的东西就可以使用了,比如map循环和filter过滤
====================================
let arr = [{},{}];

new Set([]);存放数组
new WeakSet({});存放是对象json
确认,初始往里面加东西,是不行的,最好用add去添加吧。


十一、map

map:
类似json,但是json的键(key)只能是字符串
map的可以、可以是任何类型的
使用:
let map = new Map();
map.set(key,value);//set是设置一个值
map.get(key,value);//获取一个值
map.delete(key);//删除一个值
map.has(key);//有没有这个值
map.clear();//清空
如:
let map = new Map();
map.set('sdas','sadfg');
console.log(map);
================================
循环:
for(let [key,value] of map){}
for(let key of map.keys()){}
for(let value of map.values()){}
for(let [k,v] of map.entries()){}
map.forEach((value,key)=>{
console.log(value,key);
})

weakMap//key只能是对象,现实中不建议使用

总结:
set 里面是数组,不重复,没有key,没有get方法。
map对json功能增强,key可以是任意类型值。


十二、数字的变化

map:
类似json,但是json的键(key)只能是字符串
map的可以、可以是任何类型的
使用:
let map = new Map();
map.set(key,value);//set是设置一个值
map.get(key,value);//获取一个值
map.delete(key);//删除一个值
map.has(key);//有没有这个值
map.clear();//清空
如:
let map = new Map();
map.set('sdas','sadfg');
console.log(map);
================================
循环:
for(let [key,value] of map){}
for(let key of map.keys()){}
for(let value of map.values()){}
for(let [k,v] of map.entries()){}
map.forEach((value,key)=>{
console.log(value,key);
})
=================
weakMap//key只能是对象,现实中不建议使用
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
总结:
set 里面是数组,不重复,没有key,没有get方法。
map对json功能增强,key可以是任意类型值。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值