1. 程式人生 > >ES6新特性基礎知識點總結

ES6新特性基礎知識點總結

一:ES6的一些陣列方法

1、foreach

對於一個數組

var colors=["red","green","blue"];
//ES5
for(var i=0;i<colors.length;i++){
    console.log(colors[i]);
}
//ES6
colors.forEach(function(color){
console.log(color);
})

遍歷陣列中的值並計算總和

var numbers=[1,2,3,4,5];

var sum=0;
function adder(number){
    sum+=number;
}

numbers.forEach(adder);
console.log(sum);//15

2、map

map需要返回值,如果不返回,預設undefined,map返回的是一個新的陣列。

假定一個數值陣列A,將陣列中的值以兩倍形式放到B中

var numbers=[1,2,3];
var doubleNumbers=[];
//ES5
for(var i=0;i<numbers.length;i++){
    doubleNumbers.push(numbers[i]*2);
}
console.log(doubleNumbers);
//ES6
var double=numbers.map(function(number){
return number*2;
})
console.log(double);

假定一個物件陣列A,將A中物件某個屬性的值存到B中

var cars=[
    {model:"Buick",price:"cheap"},
    {model:"BMW",price:"expensive"}
];

var prices=cars.map(function(car){
return car.price;
})
console.log(prices);// ["cheap", "expensive"]

3、filter(過濾)

假定一個數組物件A,獲取陣列中指定型別的物件放到B陣列中

var products=[
    {name:"cucumber",type:"vegetable"},
    {name:"banner",type:"fruit"},
    {name:"celery",type:"vegetable"},
    {name:"apple",type:"fruit"}
];
//ES5
var filtered=[];
for(var i=0;i<products.length;i++){
    if(products[i].type==="fruit"){
        filtered.push(products[i]);
    }
}
console.log(filtered);
//ES6 filter
var filtered=products.filter(function(product){
return product.type==="fruit";
})
console.log(filtered);

假定一個物件陣列A,過濾掉不滿足條件的物件

條件:蔬菜數量大於0,價格小於10

var products=[
    {name:"cucumber",type:"vegetable",num:0,price:20},
    {name:"banner",type:"fruit",num:10,price:1},
    {name:"celery",type:"vegetable",num:20,price:2},
    {name:"apple",type:"fruit",num:20,price:20}
];
var filtered=products.filter(function(product){
return product.type==="vegetable"
&&product.num>0
&&product.price<10
})
console.log(filtered);

假定陣列A、B,根據A中的ID,過濾到B中不符合的資料

var posts=[
    {id:4,title:"java"},
    {id:1,title:"linux"},
    {id:2,title:"js"},
    {id:4,title:"jquery"}
];

var comments={id:4,title:"vue.js"};

function commentsforposts(posts,comments){
return posts.filter(function(post){
   return post.id===comments.id;
})
}
console.log(commentsforposts(posts,comments));//posts中的id為4的會被打印出來
4、find(只會找到第一個就停止了)

假定一個數組A,找到符合條件的物件

var users=[
    {name:"JIll"},
    {name:"Alex"},
    {name:"Bill"}
];
//ES5
var user;
for(var i=0;i<users.length;i++){
    if(users[i].name==="Alex"){
        user=users[i];
        break;
    }
}
console.log(user);
//ES6
var user=users.find(function(user){
    return user.name==="Alex";
})
console.log(user);

假定物件陣列A,根據指定物件的條件找到陣列中符合條件的物件

var posts=[
    {id:1,title:"node.js"},
    {id:2,title:"vue.js"}
];

var comment={postId:1,content:"Hello World!"};

function postforcomment(posts,comment){
    return posts.find(function(post){
        return post.id===comment.postId;
    });
}

console.log(postforcomment(posts,comment));

5、every&&some

計算物件陣列中每個電腦的作業系統是否可用,大於16位的作業系統表示可用,否則不可用

var computers=[
    {name:"Apple",ram:16},
    {name:"IBM",ram:4},
    {name:"Acer",ram:32}
];
//ES5
var everycomputersCanRun=true;//所有都滿足條件才為true
var somecomputersCanRun=false;//只要有一個滿足條件就為true

for(var i=0;i<computers.length;i++){
    var computer=computers[i];
    if(computer.ram<16){
        everycomputersCanRun=false;
    }else{
        somecomputersCanRun=true;
    }
}
console.log(everycomputersCanRun);
console.log(somecomputersCanRun);
//ES6 every
var every=computers.every(function(computer){
    return computer.ram>16;
})

console.log(every);
//ES6 some
var some=computers.some(function(computer){
    return computer.ram>16;
})

console.log(some);

假定有一個註冊頁面,判斷所有input內容長度是否為0

function Filed(value){
    this.value=value;
}

Filed.prototype.validate=function(){
   return this.value.length>0;
}

var username=new Filed("");
var password=new Filed("123")

//ES5
// console.log(username.validate()&&password.validate());

//ES6
var fileds=[username,password];
var formisValid=fileds.every(function(filed){
    return filed.validate();
})
console.log(formisValid);
if(formisValid){
    //允許註冊
}else{
    //報空
}

6、reduce

計算陣列中所有值的總和

var numbers=[10,20,30];
var sum=0;


//ES5
for(var i=0;i<numbers.length;i++){
    sum+=numbers[i];
}

// console.log(sum);

//ES6  第一個引數初始化,第二個引數是傳入的形參
var sumvalue=numbers.reduce(function(sum,number){
    console.log(sum);
       return sum+number;
},10);//初始值為10

console.log(sumvalue);//10,20,40,70

將陣列中物件的某個屬性抽到另一個數組中

var  primarycolor=[
    {color:"red"},
    {color:"yellow"},
    {color:"blue"}
];

var  colors= primarycolor.reduce(function(pre,color){
    pre.push(color.color);
    return pre;
},[]);//初始化一個數組

console.log(colors);//["red","yellow","blue"]

判斷字串中字串是否對稱

function balance(string){
    return !string.split("").reduce(function(pre,char){
        if(pre<0){
            return pre;
        }//字串第一個不能為")",否則返回false
        if(char=="("){
            return ++pre;
        }
        if(char==")"){
            return --pre;
        }
        return pre;
    },0);
}

console.log(balance(")(((())))"));//不對稱返回false,對稱返回true

二:var&&let&&const

let宣告的變數有作用域的概念,更嚴謹;const宣告常量,不能改變,但是陣列能新增值

for(var i=0;i<10;i++){
    console.log(i);//0-9
}

console.log(i);//0-10

for(let i=0;i<10;i++){
    console.log(i);//0-9
}

console.log(i);//報錯

三:模版字串

let name="Herry";
function makeUppercase(word){
    return word.toUpperCase();
}
let temp=`<h1>謝謝${name},${makeUppercase('haha')}</h1>`;//ES6

let aa='<h1>歡迎歡迎</h1>'+
'<p>啦啦啦</p>';//字串拼接

document.getElementById('temp').innerHTML=temp;
document.getElementById('team').innerHTML=aa;

四:箭頭函式(1、縮減程式碼 2、改變this指向)

如圖,縮減了很多程式碼

var double=function(number){
   return number*2;
}
var double2=(number)=>{
    return number*2;
}

var double3=number=>number*2;

var double4=(number,number2)=>number+number2;

console.log(double4(20,2));

還有this指向問題

const team={
    members:["Henry","Elyse"],
    teamName:"es6",
    teamSummary:function(){
        return this.members.map(function(member){
            //當前this指向不明確了
            return `${member}隸屬於${this.teamName}小組`;
        })
    }
}

console.log(team.teamSummary());//${this.teamName}為undefined

通常ES5有兩種解決辦法

第一種解決辦法
const team={
    members:["Henry","Elyse"],
    teamName:"es6",
    teamSummary:function(){
        let self=this;//外部儲存指向
        return this.members.map(function(member){
            return `${member}隸屬於${self.teamName}小組`;
        })
    }
}

console.log(team.teamSummary());

第二種解決辦法
const team={
    members:["Henry","Elyse"],
    teamName:"es6",
    teamSummary:function(){
        return this.members.map(function(member){
            return `${member}隸屬於${this.teamName}小組`;
        }.bind(this));//bind把this繫結到函式
    }
}

console.log(team.teamSummary());

箭頭函式解決了this指向

const team={
    members:["Henry","Elyse"],
    teamName:"es6",
    teamSummary:function(){
        return this.members.map((member )=>{
            return `${member}隸屬於${this.teamName}小組`;
        })
    }
}//this指向team函式

console.log(team.teamSummary());

五:增強物件字面量(縮減程式碼)

// new Object();{}
// new Array();[]

function createBookShop(inventory){
return{
    inventory,//inventory:inventory
    inventoryValue(){
        return this.inventory.reduce((total,book)=>total+book.price,0);
    },
    priceForTitle(title){
        return this.inventory.find(book=>book.title===title.price);
    }
}
}

const inventory=[
    {title:"Vue",price:10},
    {title:"Angular",price:15}
]
// const bookShop=createBookShop(inventory);
// console.log(bookShop.inventoryValue("Vue"));

function saveFile(url,data){
    $.ajax({
        method:"POST",
        url,//url:url
        data//data:data
    });

}

const url="http://fileupload.com";
const data={color:"red"};

saveFile(url,data);

六:預設引數(優化程式碼)

兩種預設引數

function makeAjaxRequest(url,method){
if(!method){
    method="GET";
}
return method;
}

console.log(makeAjaxRequest("google.com"));
console.log(makeAjaxRequest("google.com","POST"));

//---------------------------------------------------
function makeAjaxRequest(url,method="GET"){
    return method;
    }
    
    console.log(makeAjaxRequest("google.com"));
    console.log(makeAjaxRequest("google.com","POST"));

一個例項

 function User(id){
        this.id=id;
    }
    // console.log(new User(1));

    function randomId(){
        return Math.random()*999999;
    }
    // console.log(new User(randomId()));

    function createAdminUser(user=new User(randomId())){
        user.admin=true;
        return user;
    }

console.log(createAdminUser());//不傳參時為一個隨機值

七:展開運算子(spread operator)

function addNumbersn(numbers){
    return numbers.reduce((sum,number)=>{
        return sum+number;
    },0)
}

const numbers=[1,2,3,4,5];
console.log(addNumbersn(numbers));


function addNumbersn(a,b,c,d,e){
    var numbers=[a,b,c,d,e];
    return numbers.reduce((sum,number)=>{
        return sum+number;
    },0)
}

console.log(addNumbersn(1,2,3,4,5));
function addNumbersn(...numbers){
    return numbers.reduce((sum,number)=>{
        return sum+number;
    },0)
}

console.log(addNumbersn(1,2,3,4,5,6));//這可以隨便幾個引數
var defaultColors=["red","green"];
var favouriteColor=["orange","yellow"];

// var defaultColors=defaultColors.concat(favouriteColor);
// console.log(defaultColors);

console.log([...defaultColors,...favouriteColor]);//陣列拼接

八:解構(更快,更便捷)

var expense={
    type:"es6",
    amount:"45"
}

// var type=expense.type;
// var amount=expense.amount;

const{type,amount}=expense;//解構寫法,名字和屬性必須一致
console.log(type,amount);
//es5
var savefiled={
    extension:"jpg",
    name:"girl",
    size:14040
};

function fileSammary(file){
return `${file.name}.${file.extension}的總大小${file.size}`
}
console.log(fileSammary(savefiled));
//es6
var savefiled={
    extension:"jpg",
    name:"girl",
    size:14040
};

function fileSammary({name,extension,size}){
return `${name}.${extension}的總大小${size}`
}
console.log(fileSammary(savefiled));
const names=["Henry","Bucky","Emily"];

// 解構
const[name1,name2,name3]=names;
console.log(name1,name2,name3);

// 返回陣列個數
const {length}=names;
console.log(length);

// 結合展開運算子
const[name,...rest]=names;
console.log(rest);

let a,b;
[a,b]=[100,200];
console.log(b);
//物件陣列
const people=[
    {name:"Henry",age:20},
    {name:"Bucky",age:25},
    {name:"Emily",age:30}
];

//es5
var age=people[0].age;
console.log(age);//20

//es6解構
const[age]=people;
console.log(age);//第一個物件

const[{age}]=people;
console.log(age);//20

將陣列轉化為物件

const points=[
    [4,5],
    [10,1],
    [0,40]
];
//期望資料格式
// [
//     {x:4,y:5},
//     {x:10,y:1},
//     {x:0,y:40}
// ]

//es6
let newPoints=points.map(pair=>{
    const x=pair[0];
    const y=pair[1];
    return{x,x};
})

console.log(newPoints);
//---------------------------------
let newPoints=points.map(pair=>{
    const[x,y]=pair;
    return{x,x};
})

console.log(newPoints);
//----------------------------------
let newPoints=points.map(([x,y])=>{
    return{x,y};
});

console.log(newPoints);

九:類class

function Car(option){
    this.title=option.title;
}

Car.prototype.drive=function(){
    return "Vroom";
}

const car=new Car({title:"BMW"});
console.log(car);
console.log(car.drive());
// es5繼承
function Toyota(option){
    Car.call(this,option);//加上這個就能拿到title了
    this.color=option.color;
}
Toyota.prototype=Object.create(Car.prototype);
Toyota.prototype.constructor=Toyota;

const toyota=new Toyota({color:"red",title:"Focus"});
console.log(toyota);//只能拿到color

console.log(toyota.drive());//繼承到了drive方法
//es6 繼承
class Car{
    constructor({title}){
         this.title=title;
    }
    drive(){
        return 'vroom';
    }
}

const car=new Car({title:"BMW"});
console.log(car);
console.log(car.drive());

class Toyota extends Car{
    constructor(options){
        super(options);
        this.color=options.color;
    }
}

const toyota=new Toyota({color:"red",title:"Focus"});
console.log(toyota);
console.log(toyota.drive());

十、generator生成器(返回多次值的函式)

//斐波那契數列
function fib(max){
   var a=0,b=1,arr=[0,1];

   while(arr.length<max){
       [a,b]=[b,a+b];
       arr.push(b);
   }
   return arr;
}
console.log(fib(5));//[0,1,1,2,3]
//genertor生成器
function* fib(max){
    var a=0,b=1,n=0;
    while(n<max){
        yield a;
        [a,b]=[b,a+b];
        n++;
    }
    return;
}

for(var x of fib(10)){
    console.log(x);
}
//迭代器還原生成器結構
function nameIterator(names){
    let nextIndex=0;
    return{
        next:function(){
            return nextIndex<names.length?
            {value:names[nextIndex++],done:false}:
            {value:undefined,done:true}
        }
    }
}

// const nameArray=["Henry","Bucky","Emily"];

// const names=nameIterator(nameArray);

// console.log(names.next());
// console.log(names.next());
// console.log(names.next());
// console.log(names.next());
// console.log(names.next());

//或者
function* sayNames(){
    yield 'Henry';
    yield 'Bucky';
    yield 'Emily';
}

const name=sayNames();

console.log(name.next());
console.log(name.next());
console.log(name.next());
console.log(name.next());
//id自增(es6生成器)

function* createIds(){
    let index=1;

    while(true){
        yield index++;
    }
}

const gen=createIds();
for(var i=0;i<10;i++){
    console.log(gen.next().value);
}

十一、新的陣列結構(map)

const map1=new Map();

const key1='some string',key2={},key3=function(){};

map1.set(key1,'Value of key1');
map1.set(key2,'Value of key2');
map1.set(key3,'Value of key3');

//獲取對應value
console.log(map1.get(key1),map1.get(key2),map1.get(key3));

//獲取value的個數
console.log(map1.size);

//for of遍歷map1
for(let[key,value] of map1){
    console.log(`${key}=${value}`);
}

//only key
for(let key of map1.keys()){
    console.log(key);
}

//only value
for(let value of map1.values()){
    console.log(value);
}

//foreach遍歷
map1.forEach((value,key)=>{
    console.log(`${key}=${value}`);
})

//map1轉化為陣列
const keyValueArray=Array.from(map1);
console.log(keyValueArray);

//map1中的key轉化為陣列
const keyArray=Array.from(map1.keys());
console.log(keyArray);

//map1中的value轉化為陣列
const valueArray=Array.from(map1.values());
console.log(valueArray);

十二、新的資料型別(set,集合,都可以儲存任何資料型別,但是唯一)

const set1=new Set();

//往set1中新增資料
set1.add(100);
set1.add("A String");
set1.add({name:"Henry"});
set1.add(true);
set1.add(100);//不顯示,不可以重複新增

console.log(set1);

const set2=new Set([1,true,'string']);//初始化
console.log(set2);

// //計算set1中的資料個數
console.log(set1.size);

//檢查set中是否擁有對應的值
console.log(set1.has(100));
console.log(set1.has(50+50));

console.log(set1.has({name:"Henry"}));//匹配的不是值,是地址,所以列印為false

//刪除set中的內容
set1.delete(100);
console.log(set1);

//for of 遍歷set
for(let item of set1){
    console.log(item);
}

//foreach遍歷
set1.forEach((value)=>{
    console.log(value);
})

//將set轉換為array
const setArray=Array.from(set1);
console.log(setArray);

十三、Promise(建構函式)

promise有三種狀態
unresolved 等待任務完成
resolved 任務完成並且沒有任何問題
rejected 任務完成,但是出現問題

resolved==>then
rejected==>catch
var promise=new Promise((resolve,reject)=>{
    resolve();//Promise {<resolved>: undefined}
    reject();//Promise {<rejected>: undefined}
});
console.log(promise);
var promise=new Promise((resolve,reject)=>{
    // resolve();//只能呼叫then方法
    reject();//只能呼叫catch方法
})

promise
.then(()=>console.log("成功,沒有任何問題!"))
.then(()=>console.log("成功,可以無限呼叫.then方法!"))

.catch(()=>console.log("uh oh,出現了重大問題!"))

十四、新的http請求方法(fetch)

//3秒後執行then方法
let promise=new Promise((resolve,reject)=>{
    setTimeout(()=>{
        resolve();
    },3000)
})

// promise
// .then(()=>console.log("成功,沒有問題"))

let url="http://jsonplaceholder.typicode.com/posts";//正確地址
let url1="http://jsonplaceholder.typicode.com111/posts";

// console.log(fetch(url));
fetch(url)
.then(response=>response.json())
.then(data=>console.log(data))

fetch(url1)
.catch(err=>console.log("error:"+err))

fetch請求text、json、api

//fetch三種資料格式
document.getElementById('button1').addEventListener('click',getText);
document.getElementById('button2').addEventListener('click',getJson);
document.getElementById('button3').addEventListener('click',getExternal);

function getText(){
    fetch("test.txt")
    .then((res)=>res.text())
    .then(data=>{
        console.log(data);
        document.getElementById('output').innerHTML=data;
    })
    .catch(err=>console.log(err))
}

function getJson(){
    fetch("posts.json")
    .then((res)=>res.json())
    .then(data=>{
        console.log(data);
        

        let output='';
        data.forEach((post)=>{
            output+=`<li>${post.title}</li>`;
        })
        document.getElementById('output').innerHTML=output;
    })
    .catch(err=>console.log(err))
}

//請求網路api
function getExternal(){
    fetch("https://api.github.com/users")
    .then((res)=>res.json())
    .then(data=>{
        console.log(data);
        

        let output='';
        data.forEach((user)=>{
            output+=`<li>${user.login}</li>`;
        })
        document.getElementById('output').innerHTML=output;
    })
    .catch(err=>console.log(err))
}

封裝了fetch庫(增刪改查)

class Easyhttp{
    get(url){
        return new Promise((resolve,reject)=>{
            fetch(url)
            .then(res=>res.json())
            .then(data=>resolve(data))
            .catch(err=>reject(err))
        })
    }

    //post
    post(url,data){
        return new Promise((resolve,reject)=>{
            fetch(url,{
                method:"POST",
                headers:{
                    'Content-type':'application/json'
                },
                body:JSON.stringify(data)
            })
            .then(res=>res.json())
            .then(data=>resolve(data))
            .catch(err=>reject(err))
        })
    }

    //put
    put(url,data){
        return new Promise((resolve,reject)=>{
            fetch(url,{
                method:"PUT",
                headers:{
                    'Content-type':'application/json'
                },
                body:JSON.stringify(data)
            })
            .then(res=>res.json())
            .then(data=>resolve(data))
            .catch(err=>reject(err))
        })
    }

    delete(url){
        return new Promise((resolve,reject)=>{
            fetch(url,{
                method:"DELETE",
                headers:{
                    'Content-type':'application/json'
                },
                body:JSON.stringify(data)
            })
            .then(res=>res.json())
            .then(data=>resolve('資料刪除成功'))
            .catch(err=>reject(err))
        })
    }
}

實現這個庫

const http=new Easyhttp;


//get
const users=http.get("http://jsonplaceholder.typicode.com/users")
.then((data)=>{
    console.log(data);
})
.catch(err=>console.log(err))

//傳輸資料
const data={
    name:"Henry",
    username:"Mrs吳",
    email:"[email protected]"
};

//post
http.post("http://jsonplaceholder.typicode.com/users",data)
.then(data=>console.log(data))
.catch(err=>console.log(err))


//update user
http.put("http://jsonplaceholder.typicode.com/users/2",data)
.then(data=>console.log(data))
.catch(err=>console.log(err))


//delete user
http.delete("http://jsonplaceholder.typicode.com/users/1")
.then(data=>console.log(data))
.catch(err=>console.log(err))