JavaScript ES6 特性
JavaScript ES6 特性
下面的程式碼主要是描述以下內容:
- let是塊區作用域,不會變數提升.var也是塊做作用域,但是會變數提升。
- …展開操作符作用於陣列。
- 陣列解構賦值。
- 物件增強。
- …展開操作符作用於物件。
- 物件解構賦值。
- for/of 結合迭代。
- 類繼承。
- get/set使用。
- 字串複製(repeat)。
- 函式預設值設定。
- 箭頭函式(arrow function) =>,會保持上下文 this。
- 生成器 generator(function*), yield關鍵字(暫停執行函式,返回yield 後面的表示式)。
- promise 延時操作。
- fetch demo。
- aysnc/await。
//1.let是塊區作用域,不會變數提升.var也是塊做作用域,但是會變數提升。
{
let a = 12;
var b = 52;
}
// console.log(a)// Uncaught ReferenceError: a is not defined
console.log(b)// 52
//2. 陣列展開操作符(...) array spread operator
let cats = ["Biscuit", "Jungle"];
let dogs = ["Stella", "Camper"];
let animals = ["Smoky", "Miro", "Swimmy", ...cats, ...dogs];
//["Smoky", "Miro", "Swimmy", "Biscuit", "Jungle", "Stella", "Camper"]
console.log(animals)
//3.陣列解構賦值 destructing arrays
let [first, fifth] = ["Smoky", "Miro", "Swimmy", "Camper", "Jungle"];
console.log(first);//Smoky
console.log(fifth);//Miro
let [one, , , , five] = ["Smoky", "Miro", "Swimmy", "Camper", "Jungle"];
console.log(one);//Smoky
console.log(five);//Jungle
// 4. 物件增強
// ES5
function skierES5(name, sound) {
return {
name: name,
sound: sound,
powderYell: function () {
let yell = this.sound.toUpperCase();
console.log(`${yell}! ${yell}!`)
}
}
}
skierES5("Sendy", "yeah").powderYell();//YEAH! YEAH!
// ES6
function skierES6(name, sound) {
return {
name,
sound,
powderYell() {
let yell = this.sound.toUpperCase();
console.log(`${yell}! ${yell}!`)
}
}
}
skierES6("Sendy", "yeah").powderYell();//YEAH! YEAH!
//5. 展開操作符(...)作用於物件
const daytime = {
breakfast: "oatmeal",
lunch: "peanut butter and jelly"
};
const nighttime = "mac and cheese"
const backpackingMeals = {
...daytime,
nighttime
}
//{breakfast: "oatmeal", lunch: "peanut butter and jelly", nighttime: "mac and cheese"}
console.log(backpackingMeals);
// 6.物件解構賦值
const { title, price } = {
title: "Rebuen",
price: 7,
description: "A classic",
ingredients: ["bread", "corned beef", "dressing", "sauerkraut", "cheese"]
}
console.log(title, price)//Rebuen 7
const vacation = {
destination: "Chile",
travelers: 2,
activity: "skiing",
cost: "so much"
}
function marketing({ destination, activity }) {
return `Come to ${destination} and do some ${activity}`;
}
console.log(marketing(vacation))//Come to Chile and do some skiing
//7.for/of 結合迭代
for (let letter of "javascript") {
console.log(letter)
// j
// a
// v
// a
// s
// c
// r
// i
// p
// t
}
let topics = new Map();
topics.set("HTML", "/topic/html");
topics.set("CSS", "/topic/css");
topics.set("Javascript", "/topic/javascript");
for (let topic of topics) {
// ["HTML", "/topic/html"]
// ["CSS", "/topic/css"]
// ["Javascript", "/topic/javascript"]
console.log(topic)
}
//8. 類繼承
class Vehicle {
constructor(description, wheels) {
this.description = description;
this.wheels = wheels;
}
describeYourself() {
console.log(`I am a ${this.description} with ${this.wheels}`);
}
}
class SemiTruck extends Vehicle {
constructor() {
super("semi truck", 18);
}
}
let groceryStoreSemi = new SemiTruck();
groceryStoreSemi.describeYourself();//I am a semi truck with 18
//9. get set使用 個人感覺很變扭,沒必要這樣做
class Hike {
constructor(distance, pace) {
this.distance = distance;
this.pace = pace;
}
get lengthInHours() {
return `${this.calcLength()} hours`;
}
calcLength() {
return this.distance / this.pace;
}
}
const mtTallac = new Hike(10, 2);
console.log(mtTallac.lengthInHours)//5 hours
//10. string.repeat
console.log("Hi".repeat(3));//HiHiHi
//11. 函式設定預設值
function add(x = 5, y = 6) {
console.log(x + y);
}
console.log(add())//11
//12. 箭頭函式arrow function
// ES5
// let studentList = function(students){
// console.log(students);
// }
// ES6
let studentList = (students) => {
console.log(students);
}
studentList(["A", "B", "C"])//["A","B","C"]
//ES5
let person = {
first: "Angie",
hobbies: ["bike", "hike", "ski"],
printHobbies: function () {
_this = this;
this.hobbies.forEach(function (hobby) {
let string = `${_this.first} likes to ${hobby}`;
console.log(string);
});
}
};
// Angie likes to bike
// Angie likes to hike
// Angie likes to ski
person.printHobbies();
//ES6 arrow function
let personES6 = {
first: "Angie",
hobbies: ["bike", "hike", "ski"],
printHobbies: function () {
this.hobbies.forEach((hobby) => {
let string = `${this.first} likes to ${hobby}`;
console.log(string);
});
}
}
// Angie likes to bike
// Angie likes to hike
// Angie likes to ski
personES6.printHobbies();
// 13. 生成器 generator(function*), yield關鍵字(暫停執行函式,返回yield 後面的表示式)。
function* director() {
yield "Three";
yield "Two";
yield "One";
yield "Action";
}
let countdown = director();
console.log(countdown.next().value);
console.log(countdown.next().value);
console.log(countdown.next().value);
console.log(countdown.next().value);
//14.promise 延時操作
const delay = (seconds) =>
new Promise((resolves, reject) => {
if (typeof seconds !== "number") {
reject(new Error("seconds must be a number"));
}
setTimeout(resolves, seconds * 1000)
});
delay(2).then(() => console.log("2 sec"));//2 sec
delay("one").then(() => console.log("1 sec"));//seconds must be a number
//15. fetch demo
let getSpacePeople = () =>
fetch("http://api.open-notify.org/astros.json")
.then(res => res.json())
let spaceNames = () =>
getSpacePeople()
.then(json => json.people)
.then(people => people.map(p => p.name))
.then(names => names.join(","));
//Sergey Ryzhikov,Kate Rubins,Sergey Kud-Sverchkov,Mike Hopkins,Victor Glover,Shannon Walker,Soichi Noguchi
spaceNames().then(console.log);
//16. async await
const gtihubReuqest = async (login) => {
let response = await fetch(`https://api.github.com/users/${login}`);
let json = await response.json();
let summary = `${json.name}, ${json.company}`;
console.log(summary)
};
gtihubReuqest("Tony");//Tony Narlock, @peergradeio
相關文章
- 前端-JavaScript新特性(ES6)前端JavaScript
- javascript ES6 新特性之 解構JavaScript
- ES6新特性:JavaScript中的Reflect物件JavaScript物件
- ES6新特性:JavaScript中的Map和WeakMap物件JavaScript物件
- ES6新特性
- ES6核心特性
- JavaScript回顧00:字串,陣列,物件和ES6新特性JavaScript字串陣列物件
- ES6新特性:JavaScript中內建的延遲物件PromiseJavaScript物件Promise
- ES6:下一版本的JavaScript的新特性JavaScript
- es6核心特性圖
- ES6特性之:類
- es6新特性分享
- ES6新特性總結
- ES6 新增特性小結
- 玩轉ES6新特性
- ES6 新特性之SymbolSymbol
- ES6常用的新特性
- 淺析ES6新特性
- ES6新特性:JavaScript中Set和WeakSet型別的資料結構JavaScript型別資料結構
- ES6新特性Promise詳解Promise
- ES6的全新特性:模板字串字串
- 使用JavaScript ES6的新特性計算Fibonacci(非波拉契數列)JavaScript
- JavaScript ES6 Promiss物件JavaScript物件
- 筆記:JavaScript ES6筆記JavaScript
- 1.5萬字概括ES6全部特性
- 帶你總結ES6的特性
- 簡單說說ES6新特性
- ES6常用的新特性總結
- es6新特性之 class 基本用法
- Nodejs原生支援的ES6特性NodeJS
- ES6中的新特性:Iterables和iterators
- ES6語言特性的總結(3)
- ES6語言特性的總結(1)
- ES6語言特性的總結(2)
- es6新語法新特性總結(上)
- ES6特性之:引數預設值
- Node.js 4.0的ES6新特性。Node.js
- ES6/JavaScript一些‘巧用’JavaScript