ES6語法總結

ES6 語法講解


ECMAScript是JavaScript的標準(語法規範),javascript用於遵循這個規範。javascript

  • ES6並非兼容全部瀏覽器,須要使用Babel轉爲ES5語法(ES5語法全部瀏覽器都兼容)。
  • Visual Studio Code下載插件:Bracket pair Colorizer(顏色高亮)、JavaScript(ES6)code(es6語法提示)、live server(vscode保存代碼後,頁面當即刷新,不須要手動刷新頁面)

注: live server使用:vue

vscode編輯器頁面中右擊,選擇 「Open with live server」,便可開啓保存後就刷新頁面的效果,在vscode編輯器最底部有「port:5500」,點擊後便可關閉此功能。

一、數組方法

迭代器函數:

(1)、forEach

應用場景:java

//forEach使用姿式一:
var numbers = [1, 2, 3, 4, 5],
    sum = 0;
    numbers.forEach(function(item) {
    sum += item;
});
console.log(sum); //結果:15

//forEach使用姿式二:
var numbers = [1, 2, 3, 4, 5],
  sum = 0;
function adder(item) {
  sum += item;
}
//直接調用adder函數,注意不加括號
numbers.forEach(adder);
console.log(sum); //結果:15

注意:map和forEach區別是:map有返回值,而forEach沒有返回值。jquery

(2)、map

注:map須要返回值,若是不給return,默認返回undefined,map返回的是一個新數組。

應用場景1:假定有一個數值數組A,將A數組的數值以雙倍的形式放到B數組。es6

var numbers = [1, 2, 3];
var newNumbers1 = numbers.map(function(item) {
  return item * 2;
});
console.log(newNumbers1); // 結果:[2,4,6]

應用場景2:假定有一個對象數組A,將A數組中對象某個屬性的值存儲在B數組中。ajax

var cars = [
  {
    model: "mini",
    price: 200
  },
  {
    model: "nio",
    price: 300
  }
];
var prices = cars.map(function(item) {
  return item.price;
});
console.log(prices); //結果:[200, 300]

(3)、filter

應用場景1:假定有一個對象數組A,獲取數組中指定類型的對象放到B數組中。json

var products = [
  {
    name: "cucumber",
    type: "vegetable"
  },
  {
    name: "apple",
    type: "fruit"
  },
  {
    name: "orange",
    type: "fruit"
  }
];
var filters = products.filter(function(item) {
  return item.type == "fruit";
});
console.log(filters); 
//結果:[{name: "apple", type: "fruit"},{name: "orange", type: "fruit"}]

應用場景2:假定有一個對象數組A,過濾掉不知足一下條件的對象,條件:水果 ,價格小於10,數量大於0。跨域

var products = [
  {
    name: "cucumber",
    type: "vegetable",
    quantity: 10,
    price: 5
  },
  {
    name: "apple",
    type: "fruit",
    quantity: 0,
    price: 5
  },
  {
    name: "orange",
    type: "fruit",
    quantity: 1,
    price: 2
  }
];
var filters = products.filter(function(item) {
  //使用&符號將條件連接起來
  return item.type === "fruit" && item.quantity > 0 && item.price < 10;
});
console.log(filters);
//結果:[{name: "orange", type: "fruit", quantity: 1, price: 2}]

應用場景3:假定有對象A和數組B,根據A中id值,過濾掉B中不符合的數據。數組

var post = { id: 1, title: "A" };
var comments = [
  { postId: 3, content: "CCC" },
  { postId: 2, content: "BBB" },
  { postId: 1, content: "AAA" }
];
function commentsPost(post, comments) {
  return comments.filter(function(item) {
    return item.postId == post.id;
  });
}
console.log(commentsPost(post, comments));
//結果:[{postId: 1, content: "AAA"}],返回的是數組

注意:filter和find區別:filter返回的是數組,find返回的是對象。promise

(4)、 find

應用場景1:假定有一個對象數組A,找到符合條件的對象

var users = [
  { name: "jack", age: 12 },
  { name: "alex", age: 15 },
  { name: "eva", age: 20 }
];
var user = users.find(function(item) {
  return (item.name = "eva");
});
console.log(user);
//結果:{ name: "eva", age: 20 }
注:find()找到第一個元素後就不會在遍歷其後面的元素,因此若是數組中有兩個相同的元素,他只會找到第一個,第二個將不會再遍歷了。

應用場景2:假定有一個對象數組A,根據指定對象的條件找到數組中符合條件的對象。

var post = { id: 1, title: "AAA" };
var comments = [
  { postId: 3, content: "CCC" },
  { postId: 2, content: "BBB" },
  { postId: 1, content: "AAA" }
];
function commentsPost(post, comments) {
  return comments.find(function(item) {
    return item.postId == post.id;
  });
}
console.log(commentsPost(post, comments));
//結果:{postId: 1, content: "AAA"},返回的是對象

(5)、every

總結:一假即假 ,並且只要有一個元素是假,其後面的元素將再也不遍歷。

(6)、some

總結:一真即真
使用場景:假定有幾臺電腦,判斷其操做系統是否都大於16
var computers = [
  { name: "mac", ram: 32 },
  { name: "mac", ram: 8 },
  { name: "IBM", ram: 16 },
  { name: "IBM", ram: 64 }
];
var everyComputerCan;
var someComputerCan;
//判斷每個元素的ram是否都大於16
var everyBoolan = computers.every(function(item) {
  return item.ram > 16;
});
//判斷元素的ram是否都大於16
var someBoolean = computers.some(function(item) {
  return item.ram > 16;
});
console.log(everyBoolan); //結果:false
console.log(someBoolean);//結果: true

(7)、reduce

應用場景1:計算數組中全部值總和

var numbers = [1, 2, 3];
var sumVal = numbers.reduce(function(sum, number) {
  return sum + number;
  //0是sum的初始化值
}, 0);
console.log(sumVal);

應用場景2:將對象數組中對象的某個屬性抽離到另一個數組中

var colors = [
  { color: "red" }, 
  { color: "green" }, 
  { color: "black" }
];
var colorsNew = colors.reduce(function(colorArr, colors) {
  colorArr.push(colors.color);
  return colorArr;
}, []);
console.log(colorsNew);
//結果:["red", "green", "black"]

應用場景3:判斷字符串中括號是否對稱

function balanceParents(string) {
  return !string.split("").reduce(function(previous, char) {
    if (char == "(") {
      return ++previous;
    }
    if (char == ")") {
      return --previous;
    }
    return previous;
  }, 0);
}
console.log(balanceParents("(())aaadsd))"));//結果:false

二、新語法

(1)、 const

const 定義的常量後不能更改其值,可是數組是能夠建立後,添加元素的。

const arr = [];
arr[0] = 1;//不會報錯
console.log(arr);

const str = "abc";
str = "ddd";//報錯:Assignment to constant variable.

(2)、模板字符串

定義:模板字符串是指在js語句中使用``符號包含的字符串。
let age = 10;
function makeUppercase(item) {
  return item.toUpperCase();
}
 //模板字符串中語法:
//在模板字符串中使用${方法名()}調用某得方法
//在模板字符串中使用${}獲取變量的值
var template = `<h1>內容</h1>
  <spn>${makeUppercase("hello")}</spn>
  <p>${age}</p>`;
document.getElementById("name").innerHTML = template;

頁面結果顯示:

**內容**
HELLO
10

(3)、箭頭函數

const team = {
  merbers: ["heny", "jack"],
  teamName: "A組",
  //箭頭函數(ES6語法)
  teamSummary: function() {
    return this.merbers.map(item => {
      //this指向team對象
      return `${item}隸屬於${this.teamName}小組`;
    });
  },
  //self保存this(ES5語法)
  teamSummary1: function() {
    let self = this;
    return this.merbers.map(function(item) {
      return `${item}隸屬於${self.teamName}小組`;
    });
  },
  //bind綁定this(ES5語法)
  teamSummary2: function() {
    return this.merbers.map(
      function(item) {
        return `${item}隸屬於${this.teamName}小組`;
      }.bind(this)
    );
  }
};
console.log(team.teamSummary());
console.log(team.teamSummary1());
console.log(team.teamSummary2());

(4)、 加強對象字面量

目的:減小沒必要要的代碼,好比咱們使用vue開發時:
new Vue({
  el: "#app",
  //此處的router就是一種簡寫形式(即加強對象字面量),其完整寫法爲:"router:router"
  router,
  components: { App },
  template: "<App/>"
});

同理,對於jquery中的ajax請求:

$.ajax({
 //此處的url和data就是簡寫形式(即加強對象字面量),完整的爲"url:url,data:data"
 url,
 data,
 methods:"POST"
});

(5)、擴展運算符

應用場景1:將單獨的數值組成數組返回

//使用"..."(擴展運算符)自動將傳入的參數組成數組:numbers
function addNumber(...numbers) {
  return numbers.reduce((sum, item) => {
    return sum + item;
  }, 0);
}
console.log(addNumber(1, 2, 3, 4, 5, 6, 7, 8, 9, 10));
//結果:55

應用場景2:組合多個數組

var defaultNum = [1, 2, 3, 4, 5];
var myNum = [10, 20];
var yourNum = [9, 8, 7];
console.log([11, 22, 33, ...defaultNum, ...myNum, ...yourNum]);
//結果: [11, 22, 33, 1, 2, 3, 4, 5, 10, 20, 9, 8, 7]

(6)、 解構

應用場景1:對象屬性解構

var obj = {
  name: "Zhangfei",
  age: 26
};
//注意:結構的變量的名字要和對象中的名字保持一致,找不到的將會返回undefined
const { name, age, data } = obj;
console.log(name, age, data);
//結果:Zhangfei  26  undefined

應用場景2:函數參數解構

var obj = {
  name: "zhangsan",
  age: 12
};
function myObj({ name, age }) {
  return `${name},年齡:${age}歲`;
}
console.log(myObj(obj));
//結果:zhangsan,年齡:12歲

應用場景3:數組元素的解構

const names = ["hery", "bucky", "emily"];
const [name1, name2, name3] = names;
console.log(name1, name2, name3);
//結果:demo.js:3 hery bucky emily

應用場景4:數組長度的解構

const names = ["hery", "bucky", "emily"];
//使用{}解析數組獲得數組長度
const { length } = names;
console.log(length);

應用場景5:結構和展開運算符搭配使用

const names = ["herry", "emliy", "buky"];
const [name1, name2, ...rest] = names;
console.log(name1);  //herry
console.log(name2);  //emliy
console.log(rest);  //['buky']

應用場景6:將數組轉爲對象

const points = [[1, 2], [3, 4], [5, 6]];
var newPoints = points.map(function(item) {
  const [x, y] = item;
  return { x, y };
});
console.log(newPoints);
//結果:[{x: 1, y: 2},{x: 3, y: 4},{x: 5, y: 6}]

三、新語法

(1)、 面向對象class(萬事皆對象)

class Car {
  constructor(options) {
    this.title = options.title;
  }
  drive() {
    return "vromm";
  }
}
//這裏須要繼承Car類,拿到構造函數中的title屬性
class Toyota extends Car {
  constructor(options) {
    //使用super繼承父類的構造函數中的屬性,這樣toyota.title纔不會是undefined
    super(options);
    this.color = options.color;
  }
}
const toyota = new Toyota({ color: "red", title: "MINI" });
console.log(toyota.title); //MINI

(2)、 generator生成器(能夠返回屢次的函數)

//斐波那契數列
//生成器函數是:在function後面加上*的函數
function* fib(max) {
  var a = 0,
    b = 1,
    n = 0;
  while (n < max) {
    yield a;//yield關鍵字
    [a, b] = [b, a + b];
    n++;
  }
  return;
}
for (var x of fib(5)) {
  console.log(x);
}
//結果:0 1 1 2 3

(3)、 數據結構:map (與上面所講的數組的map方法不是一回事)

注:與對象不一樣的是,鍵和值可使任意類型的。

應用場景1: 建立map數據結構

const map1 = new Map();
//設置key鍵
const key1 = "name",
  key2 = {},
  key3 = function() {};
//設置value
map1.set(key1, "key1‘s value");
map1.set(key2, "key2’s value");
map1.set(key3, "key3‘s value");
console.log(map1.get("name"));  //key1‘s value
console.log(map1.get(key2));   //key2’s value
console.log(map1.get(key3));  //key3‘s value

應用場景2:獲取map數據結構的長度

console.log(map1.size); //3

應用場景3:遍歷map數據結構的key和value

for(var [key,value] of map1){
    console.log(`${key} = ${value}`);
}
//結果:name = key1‘s value
        [object Object] = key2’s value
        function () {} = key3‘s value
for (let item of map1.keys()) {
  console.log(item);
}
//結果:name         {}           ƒ () {}
for (let item of map1.values()) {
  console.log(item);
}
//結果:key1’s value         key2’s value          key3‘s value

應用場景4:將map數據結構的key和value轉爲數組

const keyArr = Array.from(map1.keys());
console.log(keyArr);
//結果:["name", {…}, ƒ]
const valueArr = Array.from(map1.values());
console.log(valueArr);
//結果:["key1‘s value", "key2’s value", "key3‘s value"]

(4)、 數據結構:set

set即集合:能夠存儲任何類型數據,而且是惟一的。

應用場景1:建立set

var set = new Set();
set.add(100);
set.add("asdf");
set.add({ name: "herry" });
set.add("fn");
set.add(100);
console.log(set);

//結果:{100, "asdf", {…}, "fn"}

應用場景2:set長度計算

console.log(set.size);
//結果: 4

應用場景3:判斷set中是否包含某項

console.log(set.has(100));
console.log(set.has({ name: "herry" }));
//結果:true   
        false(由於對象在內存中存儲的是地址,而不是值,因此是false)

應用場景4:刪除set中某元素

set.delete("fn");
console.log(set);
//結果:{100, "asdf", {…}}

應用場景5:遍歷set

for (let item of set) {
  console.log(item);
}
//結果:100              "asdf"             {…}

應用場景6:set轉爲數組

const arr = Array.from(set);
console.log(arr);
//結果:[100, "asdf", {…}]

四、數據請求(異步)

(1)、 promise

A[Promise] --> B(unresolved) 
    A[Promise] --> c(resolved) 
    A[Promise] --> d(rejected)
    c --> e[then]
    d --> f[catch]

應用場景1:

let promise = new Promise((resolve, reject) => {
  resolve();
  //   reject();
});
promise
  .then(() => {
    console.log("no problem");
  })  //resolve後走then()方法
  .then(() => {
    console.log("能夠無限調用then");
  .catch(() => {
    console.log("uh oh,出問題啦");
  }); //reject後走catch()方法

(2) fetch

fetch方法定義:

①、option(參數選項):

  • method:get | post 等方法
  • headers:任何你想加到請求中的頭,能夠是對象字面量的方式也能夠是經過 Headers
  • body:發送給服務器的信息, 能夠是JSON, ufferSource, FormData, URLSearchParams, 或 USVString。注意get和HEAD請求沒有body
  • mode:請求模式, 可選值爲 cors, no-cors, same-origin, 或 navigate,cors-with-forced-preflight。默認值應該爲 cors。但在Chrome中,Chrome 47 以前的版本默認值爲 no-cors ,自Chrome 47起,默認值爲same-origin。--MDN Request
  • credentials:在請求中是否須要憑據。在請求數據中根據是否須要攜帶Cookie 來設置其值,可選值爲omit(在請求中不懈怠認證憑據(Cookie)), same-origin(在同原站點下包含憑據), 或 include(對全部網站包含認證憑據)
  • cache:如何處理緩存,可取值有 default | no-store | no-cache | reload | force-cache | only-if-cached
  • redirect:對重定向的處理,可取值 follow, error, redirect
  • referrer:一個指定了no-referrer, client, 或一個 URL的 USVString 。默認值是client.
  • integrity: 包括請求的 subresource integrity 值 (e.g., sha256-BpfBw7ivV8q2jLiT13fxDYAe2tJllusRSZ273h2nFSE=).

②、mode 參數便於CORS,設置不一樣的值可使在不一樣的請求方式下,使得請求有效。

  • cors:在同域和帶有CORS響應頭的跨域下能夠請求成功
  • no-cors:經常使用於在跨域不帶CORS場景下,此時請求發出而且會有響應,可是此時type爲「opaque」, status爲0 ,js獲取不到返回數據。
  • same-origin:在同域下請求
  • cors-with-forced-preflight:在請求前進行preflight 檢查

應用場景1:fetch實例

let url = "http://jsonplaceholder.typicode.com/posts";
fetch(url)
  .then(response => response.json())  //fetch方法中先獲取response.json()
  .then(data => console.log(data))
  .catch(error => console.log(error));
//結果:返回的是接口詳細數據

應用場景2:fetch的三種請求數據方式

document.getElementById("button1").addEventListener("click", getText);
document.getElementById("button2").addEventListener("click", getJson);
document.getElementById("button3").addEventListener("click", getInternet);

//獲取本地文本數據
function getText() {
  fetch("test.txt")
    .then(res => res.text())
    .then(data => {
      document.getElementById("output").innerHTML = data;
    })
    .catch(error => {
      console.log(error);
    });
}
//獲取本地json數據
function getJson() {
  fetch("data.json")
    .then(res => res.json())
    .then(data => {
      console.log(data);
      var str = "";
      data.forEach(function(item) {
        str += `<h2>${item.title}</h2><h3>${item.body}</h3>`;
      });
      document.getElementById("output").innerHTML = str;
    })
    .catch(error => {
      console.log(error);
    });
}
//獲取接口數據
function getInternet() {
  fetch("http://jsonplaceholder.typicode.com/users")
    .then(res => res.json())
    .then(data => {
      console.log(data);
      var str = "";
      data.forEach(function(item) {
        str += `<h2>${item.id}</h2><h3>${item.name}</h3>`;
      });
      document.getElementById("output").innerHTML = str;
    })
    .catch(error => {
      console.log(error);
    });
}
//data.json數據
[
  {
    "title": "es6",
    "body": "I am es6"
  },
  {
    "title": "es7",
    "body": "I am es7"
  },
  {
    "title": "es8",
    "body": "I am es8"
  }
]
//test.txt數據
這是本地文本數據測試的!!!

應用場景3:封裝fetch(使用ES6語法promise,對照下面ES7語法封裝)

//首先封裝fetch 方法
class EasyHttp {
  //get方法
  get(url) {
    return new Promise((resolve, reject) => {
      fetch(url)
        .then(rsp => rsp.json())
        .then(data => resolve(data))
        .catch(error => reject(error));
    });
  }
  //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(error => reject(error));
    });
  }

  //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(error => reject(error));
    });
  }

  //delete請求
  delete(url) {
    return new Promise((resolve, reject) => {
      fetch(url, {
        method: "DELETE",
        headers: { "Content-type": "application/json" }
      })
        .then(rsp => rsp.json())
        .then(data => resolve("數據刪除成功!"))
        .catch(error => reject(error));
    });
  }
}
//main.js數據中調用封裝好的fetch方法
const http = new EasyHttp();
//get請求(獲取數據)
http
  .get("http://jsonplaceholder.typicode.com/users")
  .then(data => {
    console.log(data);
  })
  .catch(error => {
    console.log(error);
  });

//post請求數據(增長數據)
const data = {
  name: "Herry",
  username: "恆瑞"
};
http
  .post("http://jsonplaceholder.typicode.com/users", data)
  .then(data => console.log(data))
  .catch(error => {
    console.log(error);
  });

//put請求(更新數據)
const data = {
  name: "Herry",
  username: "恆瑞"
};
http
  .put("http://jsonplaceholder.typicode.com/users/2", data)
  .then(data => console.log(data))
  .catch(error => {
    console.log(error);
  });

//delete請求(刪除數據)
http
  .delete("http://jsonplaceholder.typicode.com/users/2")
  .then(data => console.log(data))
  .catch(error => {
    console.log(error);
  });

五、es7方法

(1)、 async 和 await

應用場景1:async 和 await基本使用

//使用async定義函數,返回的是一個promise對象
async function myFun() {
  const promise = new Promise((resolve, reject) => {
    setTimeout(() => resolve("Hello"), 1000);
  });
  const error = false;
  if (!error) {
    //這裏await等待promise返回結果
    const rsp = await promise;
    return rsp;
  } else {
    await Promise.reject(new Error("error:報錯了!"));
  }
}
myFun()
  .then(data => {
    console.log(data);
  })
  .catch(error => {
    console.log(error);
  });
  //輸出結果:Hello

應用場景2:async 和 await調用接口

async function getUsers() {
  //await等待接口調用成功
  const response = await fetch("http://jsonplaceholder.typicode.com/users");
  //await等待數據解析成功
  const rsp = await response.json();
  return rsp;
}

getUsers()
  .then(data => console.log(data))
  .catch(error => console.log(error));
//返回結果:users數據信息

應用場景3:ES7語法使用async 和 await從新封裝fetch(對照上面的promise封裝fetch)

//首先封裝fetch方法:
class EasyHttp {
  //get方法
  async get(url) {
    const response = await fetch(url);
    const rspData = await response.json();
    return rspData;
  }
  //post請求
  async post(url, data) {
    const response = await fetch(url, {
      method: "POST",
      headers: {
        "Content-type": "application/json"
      },
      body: JSON.stringify(data)
    });
    const rspData = await response.json();
    return rspData;
  }

  //put請求
  async put(url, data) {
    const response = await fetch(url, {
      method: "PUT",
      headers: {
        "Content-type": "application/json"
      },
      body: JSON.stringify(data)
    });
    const rspData = await response.json();
    return rspData;
  }

  //delete請求
  async delete(url) {
    const response = await fetch(url, {
      method: "DELETE",
      headers: { "Content-type": "application/json" }
    });
    const rspData = await response.json();
    return rspData;
  }
}
//main.js數據中調用封裝好的fetch方法
const http = new EasyHttp();
//get請求(獲取數據)
http
  .get("http://jsonplaceholder.typicode.com/users")
  .then(data => {
    console.log(data);
  })
  .catch(error => {
    console.log(error);
  });

//post請求數據(增長數據)
const data = {
  name: "Herry",
  username: "恆瑞"
};
http
  .post("http://jsonplaceholder.typicode.com/users", data)
  .then(data => console.log(data))
  .catch(error => {
    console.log(error);
  });

//put請求(更新數據)
const data = {
  name: "Herry",
  username: "恆瑞"
};
http
  .put("http://jsonplaceholder.typicode.com/users/2", data)
  .then(data => console.log(data))
  .catch(error => {
    console.log(error);
  });

//delete請求(刪除數據)
http
  .delete("http://jsonplaceholder.typicode.com/users/2")
  .then(data => console.log(data))
  .catch(error => {
    console.log(error);
  });
相關文章
相關標籤/搜索