1. 程式人生 > 實用技巧 >ES6(嚴格模式,let&const,箭頭函式,解構賦值,字串擴充套件方法,Symbol,Set和Map,生成器函式)

ES6(嚴格模式,let&const,箭頭函式,解構賦值,字串擴充套件方法,Symbol,Set和Map,生成器函式)

嚴格模式

<script type="module">
// 模組開發,自動嚴格模式
<script>
​
"use strict";//嚴格模式
​
// 變數必須定義後使用
var a=4;
function abc(){
    var a=3;
    console.log(window.a);
}
abc();//4 
console.log(window.a); //4
​
// 不允許引數名重複
function fn(a,a){
    console.log(a);
}
fn(3,5); //Duplicate parameter name not allowed in this context
​
var div=document.querySelector("div");
div.style.width="100px";
div.style.height="100px";
div.style.backgroundColor="red";
div.style.border="1px solid #000000"; 
// 嚴格模式不允許使用with  
with(div.style){
    width="100px";
    height="100px";
    backgroundColor="red";
    border="1px solid #000000";
} 
​
// 只讀屬性都不是能修改
div.offsetLeft=300;
var str="";
str.length=0;//都不能更改
​
var obj={};
Object.defineProperty(obj,"a",{
    writable:false//只讀屬性
})
obj.a=10; //報錯
​
// var num=0xFF;
// var num=065;//嚴格模式八進位制不能使用
​
// 不能刪除不可刪除的屬性
var arr=[1,2];
delete arr.length;
​
var obj={}
Object.defineProperty(obj,"a",{
    configurable:false//不可刪除屬性
});
delete obj.a; 
​
var obj1={};
var obj2={};
var obj3={};
var obj4={};
​
// 反射  將字串反射為該字串變數名的物件
for(var i=1;i<5;i++){
    eval("obj"+i).a=i*10;
}
console.log(obj1,obj2,obj3,obj4) 
​
for(var i=0;i<6;i++){
    eval("div"+i).innerHTML=i;
}
​
// eval 和 arguments 不能重新賦值
//arguments.callee 不能使用
//arguments.callee.caller  不能使用
​
function abc(){
    // 在頂層函式中this不能執行window了,是undefined
    console.log(this);
}
abc(); //undefined

let&const

var a=3;
​
for(var i=0;i<10;i++){
​
}
​
let a=3;
console.log(a);//3
for(let i=3;i<10;i++){
    // 僅屬於這個語句塊中
}
function fn(){
    console.log(a);//3
    // console.log(i);//i is not defined
    if(a>2){
        let b=10;//範圍僅在if中
    }
    // console.log(b);//b is not defined
}
fn();
​
// let定義的變數僅在{}作用域內使用
// var 和 let可以混合使用
​
// const  常量
const EVENT_ID="event_id";
// 常量不可以修改值
const EVENT_ID;//不能這樣
​
const obj={a:1,b:2};
obj={a:4,b:5};//這樣做可以防止obj的引用地址發生改變
obj.a=10;
obj=null;//會一直存在堆中,無法銷燬

箭頭函式

var fn=()=>{
    var a=3;
    var b=4;
    return a+b;
}
var sum=fn();
console.log(sum);//7
​
var fn=function(){
    var a=3;
    var b=4;
    return a+b;
} 
​
// 如果函式中僅有一句話,並且這句話是return返回可以省略{}和return
var fn=(a,b)=>a+b;
​
var fn=function(a,b){
    return a+b;
} 
​
var arr=[1,2,3,4,5];
// 箭頭函式中如果僅有一個引數可以省略小括號
// 如果沒有引數,或者由一個以上的引數不能省略小括號
if(arr.every(item=>item>0)){
​
}
var bool=arr.every(function(item){
    return item>0
});
if(bool){
​
} 
​
var arr=arr.filter(item=>item>3);
console.log(arr);
​
var sum=arr.reduce((value,item)=>value+=item);
console.log(sum); 
​
arr.sort((a,b)=>b-a);
console.log(arr); 
​
setInterval(()=>{
​
},16) 
​
var obj={
    a:function(){
        // ES5的方法
        console.log("a")
    },
    b(){
        // ES6的方法
        console.log("b");
    },
    c:()=>{
        // ES6箭頭函式
        console.log("c");
    }
}
obj.a();
obj.b();
obj.c(); 
​
document.addEventListener("click",e=>{
​
}) 
// 更改this指向
var obj={
    b:1,
    a:function(){
        document.obj=this;
        document.addEventListener("click",this.clickHandler);
    },
    clickHandler(e){
        console.log("a");
        document.removeEventListener("click",this.obj.clickHandler);
    }
} 
​
var obj={
    b:1,
    a:function(){
        document.obj=this;
        // var fn=(e)=>{
        //     console.log(this);//當函式換為箭頭函式時,
        //     // this將會被指向當前函式外this的指向
        //     this.clickHandler(e);
        // }
​
        // var fn=function(e){
        //     console.log(this);//點選的事件物件
        // }
        // document.addEventListener("click",fn);
        document.addEventListener("click",e=>this.clickHandler(e));
        this.c();
    },
    clickHandler(e){
        console.log(this);//obj
        // e.currentTarget 
        document.removeEventListener("click",this.clickHandler);
    },
    c:function(){
        console.log(this);//呼叫這個函式的物件,obj
    },
    d:()=>{
        console.log(this);//只想這個箭頭函式外的this,是這個物件
    }
} 
obj.a();//obj這個物件
obj.c();//obj這個物件
obj.d();//window(使用箭頭函式後,this指向該函式外的this指向)
​
// 箭頭函式主要可以作為改變函式中this的指向問題
​
var obj={
    a:1,
    init:function(){
        var bn=document.querySelector("button");
        bn.addEventListener("click",this.fn=e=>this.clickHandler(e));
    },
    clickHandler:function(e){
        console.log(this.a);
        e.currentTarget.removeEventListener("click",this.fn);
    }
}
obj.init(); 
​
 Utils.dragElem(document.querySelector("button"));

解構賦值

var  {a,b}={a:1,b:2};
var [c,d]=[3,4];
​
var arr=[2,3,4];
var [a,b,c]=arr;
console.log(a,b,c); 
// 函式返回多個元素,解析
function fn(){
    var a=1;
    var b=2;
    var c=3;
    a++;
    b--;
    c+=4;
    return [a,b,c];
}
var arr=fn();
console.log(arr);//[2,1,7]
​
var [a,b,c]=fn();
console.log(a,b,c); //2 1 7
​
// 可以讓引數賦初值
function fn([a,b,c=3]){
    console.log(a,b,c);
}
fn([1,2]); 
​
var [a,b,c=3]=[5,6];
var [a,b,c=3]=[5,6,7];
console.log(a,b,c);
​
function fn(a,b,c=3){
    console.log(a,b,c);
}
fn(3,5); 
​
// 陣列解析最重要的是按位解析
// 物件是按照屬性名解析
// var {a,b,c}={b:10,a:20,c:30};
// console.log(a,b,c);//20 10 30
// var {a,b,c:{a:a1,b:b1}}={a:10,b:20,c:{a:30,b:40}};
// var {a,b=100,c:{a:a1,b:b1=200}}={a:10,c:{a:30}};
// var {a,b=100,c:{a:a1,b:b1=200}}={a:10,c:{a:30,b:40}};
// console.log(a,b,c,a1,b1)
//10 20 30 30 40
//10 100 30 30 200
//10 100 30 30 40
//C不能被解構
​
function fn(){
    var a=1;
    var b=2;
    var c=3;
    return {a:1,b:2,c:3};
}
var {a,b,c}=fn();
console.log(a,b,c); //1 2 3
​
// 引數解構賦值後可以跳位,不需要按照順序寫
function fn({a,b=3,c}){
    console.log(a,b,c);
}
fn({a:10,c:20}); //10 3 20
​
// 將載入進來的物件中方法解構出來形成全域性的函式(物件內部的this將被重新指向全域性的this)
//當物件的函式用到this,不用使用解構,解構會破壞this指向
var {randomColor,ce}=Utils;
console.log(randomColor());
ce("div",{width:"50px",height:"50px",backgroundColor:randomColor()},"body");
​
// JSON解析
​
// var x=3;
// var y=4;
// [x,y]=[y,x];

字串擴充套件方法

var str="\u4e00";//不可以組合
​
console.log(str);
var div=document.querySelector("div");
var num=0x4e00;
setInterval(animation,500);
​
function animation(){
    // div.innerHTML=`\u${a}`
    num++;
    div.innerHTML=String.fromCharCode(num);
} 
​
var str="ashdjsahdwi";
console.log(str.indexOf("j")>-1);
console.log(str.search(/j/)>-1);
console.log(str.match(/j/));
console.log(/j/.test(str));
// 判斷字元在字串中是否存在
console.log(str.includes("j")); 
​
console.log("abcde".startsWith("a"));//判斷a是不是從頭開始
console.log("abcde".startsWith("b",1));//判斷從第1位開始的是不是b
console.log("car_0".startsWith("car_"));
console.log("abc_car".endsWith("_car"));
console.log("abc_car".endsWith("a",1));
​
console.log("ab".repeat(3));  字串重複
document.documentElement.style.backgroundColor="#"+(Math.floor(Math.random()*256).toString(16)).repeat(3);
​
// 字串.padStart(長度,前面補充的字元);
// 字串.padEnd(長度,後面補充的字元);
console.log("#abcde".padStart(7,Math.floor(Math.random()*16).toString(16)));
console.log("#abcde".padEnd(7,Math.floor(Math.random()*16).toString(16)));
console.log("#"+Math.floor(Math.random()*0xFFFFFF).toString(16).padStart(6,0))
​
var a=4;
console.log(`abc${a}`);
var age=30;
console.log(`小明今年${age}歲了!`);//php的語法移植了
// "小明今年{$age}歲了!"
​
alert `123`;
function fn(a){
    console.log(a);
}
fn `3`; 

Symbol

//Symbol  唯一,建立的永遠沒有相同的
var a=Symbol("a");
var b=Symbol("b");
var c=Symbol();
console.log(a.toString());
​
  // 去除魔術字串
//const RUN="run";
//const WALK="walk";
//const STAND="stand";
//const JUMP="jump"; 
const RUN=Symbol();
const WALK=Symbol();
const STAND=Symbol();
const JUMP=Symbol();
var actorStatus=RUN;
// var actorStatus="walk";
actorAction();
​
  function actorAction() {
    switch (actorStatus) {
      case RUN:
        console.log("執行跑的動畫");
        break;
      case WALK:
        console.log("執行走的動畫");
        break;
      case STAND:
        console.log("執行站立的動畫");
        break;
      case JUMP:
        console.log("執行跳躍的動畫");
        break;
    }
  } 
​
var obj={
      a:1,
      b:2
  }
​
obj.c=10;
obj.c=20; 
​
//   物件鍵值對中鍵可以是字元型也可以是Symbol型
var a="abc";
  const KEY_1=Symbol();
  var obj={
      [a]:10,
      [KEY_1]:100
  }
//   這個鍵名就不會被覆蓋
console.log(obj[KEY_1]);
obj.abc=200;
console.log(obj); 

Set和Map

var ab=new Set([1,2,3,4]);
console.log(ab);
​
// Set資料型別 無重複列表型別
// Set沒有下標,不是按照下標儲存,有序,不能使用下標迴圈遍歷
// 插入速度和刪除速度非常快
// 沒有重複元素,任何元素存在唯一性,遍歷查詢速度也非常快,但是略低於鍵值對型別
var ab=new Set();
ab.add(1);
ab.add(2);
ab.add(3);
ab.add(2);
console.log(ab);
ab.delete(2);
​
console.log(ab.has(3));//判斷這個元素是否在列表中存在
ab.clear();//清除所有資料
console.log(ab.size);//size就是長度,沒有length
​
var arr=[1,3,5,7,2,4,3,5,1,2,6,5,7,8,9,1,2,4,3,5,7,9];
arr=Array.from(new Set(arr));
console.log(arr);
​
// Set使用場景
var manager={
    list:[],
    add(elem){
        if(this.list.indexOf(elem)>-1) return;
        this.list.push(elem);
    },
    remove(elem){
        var index=this.list.indexOf(elem);
        if(index<0) return;
        this.list.splice(index,1);
    },
    update(){
        for(var i=0;i<this.list.length;i++){
            this.list[i].update();
        }
    }
​
} 
​
var manager={
    list:new Set(),
    add(elem){
        this.list.add(elem);
    },
    remove(elem){
        this.list.delete(elem);
    },
    update(){
        for(let value of this.list){
            value.update();
        }
    }
​
}
​
var times=new Date().getTime();
var ids=setInterval(animation,500);
​
function animation(){
    var obj={
        name:"obj"+new Date().getTime(),
        update(){
            console.log(this.name);
        }
    }
    manager.add(obj);
    if(new Date().getTime()-times>10000){
        clearInterval(ids);
        manager.update();
    }
} 
​
var a=new Set([1,2,3,4,5]);
a.forEach(function(value1,value2,a1){
    console.log(value1,value2,a1);
}) 
​
for(let value of a){
    console.log(value);
} 
​
// hashMap  鍵值對的資料型別
// map是一種由長度的鍵值對資料結構
// 具備陣列的長度緊密型,又具備物件的鍵值對方法
// 它的獲取,刪除,查詢,遍歷速度很快
var map=new Map();
map.set("name","xietian");
map.set("age",30);
console.log(map.size);
map.delete("name");//刪除鍵名
map.clear();//清除掉所有資料
console.log(map.get("age"))//獲取某個鍵的值
console.log(map.has("age"));//判斷某個鍵是否存在
console.log(map.values());//獲取所有值的列表
console.log(map.keys());//獲取所有鍵的列表
​
map.forEach(function(value,key,map){
    console.log(value,key);
}) 
​
for(let key of map.keys()){
    console.log(key);
}
​
for(let value of map.values()){
    console.log(value);
}
​
for(let arr of map.entries()){
    console.log(arr[0],arr[1]);
} 
​
map.set(15,15);
map.set(true,true);
var s=Symbol();
map.set(s,15);
console.log(map.get(s));
for(let key of map.keys()){
    console.log(key);
}
​
var obj={a:1,b:2};
var obj1={a:2,b:3};
map.set(obj,15);
map.set(obj1,150);
map.set(obj,obj1);
console.log(map);
​
// 任何型別都可以作為鍵使用
​
// WeakSet  WeakMap  弱引用型別
// 弱引用,就是如果其中的強引用的型別地址設定為null,弱引用的關係會自動解除
var obj={a:1,b:2};
var obj1=obj;
// obj=null;
var s=new WeakSet();
s.add(obj);
obj=null;
console.log(s);
// 弱引用的型別不可以遍歷
for(var value of s){
    console.log(value);
} 
​
var dic=new WeakMap();
// WeakMap 儲存的key必須是物件
var img=new Image();
var img1=new Image();
dic.set(img,img1);
img=null;
console.log(dic.get(img));
for(let value of dic.values()){
    console.log(value);
}

生成器函式

function *abc(a,b){
    yield a;
    yield b;
    a++;
    yield a;
    b+=10;
    yield b;
    return a+b;
}
// 生成器物件
var a=abc(3,5);
var obj=a.next();//{value:3,done:false};
//    value就是yield返回的結果,done就是是否函式允許完成
console.log(obj);
obj=a.next();
console.log(obj);
obj=a.next();
console.log(obj);
obj=a.next();
console.log(obj);
obj=a.next();
console.log(obj);
​
var obj=a.next();
console.log(obj.value)
while(!obj.done){
    obj=a.next();
    console.log(obj.value);
}
​
let aaa=abc(10,20);
for(let values of aaa){
    console.log(values);
}