前端基础:学习 ES6 新特性
目錄
一、聲明變量的兩種方式
1)、let 聲明變量(與var 聲明變量的對比)
2)、const 聲明常量(只讀變量)
二、解構(gòu)表達式
? ?1)、數(shù)組解構(gòu)
? ?2)、對象解構(gòu)
三、字符串處理
? ?1)、字符串擴展
???2)、字符串模板
四、函數(shù)優(yōu)化
? ?1)、函數(shù)參數(shù)默認值
? ?2)、不定參數(shù)
? ?3)、箭頭函數(shù)
? ?4)、實戰(zhàn):箭頭函數(shù)結(jié)合解構(gòu)表達式
五、對象優(yōu)化
? 1)、新增的API
? 2)、聲明對象簡寫
? 3)、對象的函數(shù)屬性簡寫
? 4)、對象拓展運算符
六、map 和 reduce 的使用
七、Promise 編排
1)、前言
2)、案例
3)、Promise 創(chuàng)建
4)、Promise 改造以前嵌套方式
5)、使用Promise后的嵌套方式
6)、使用函數(shù)封裝請求,優(yōu)化處理后的方式
八、模塊化
1)、什么是模塊化?
2)、export
3)、import
一、聲明變量的兩種方式
1)、let 聲明變量(與var 聲明變量的對比)
<!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><meta http-equiv="X-UA-Compatible" content="ie=edge"><title>Document</title> </head> <body><script>//?var?聲明的變量往往會越域//?let?聲明的變量有嚴格局部作用域{var?a?=?1;let?b?=?2;}console.log(a);??//?console.log(b);??//?ReferenceError:?b?is?not?defined</script> </body> </html> <!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><meta http-equiv="X-UA-Compatible" content="ie=edge"><title>Document</title> </head> <body><script>//?var?可以聲明多次//?let?只能聲明一次var?m?=?1var?m?=?2let?n?=?3let?n?=?4console.log(m)??//?2console.log(n)??//?Identifier?'n'?has?already?been?declared</script> </body> </html> <!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><meta http-equiv="X-UA-Compatible" content="ie=edge"><title>Document</title> </head> <body><script>//?var?會變量提升//?let?不存在變量提升console.log(x);??//?undefinedvar?x?=?10;console.log(y);???//ReferenceError:?y?is?not?definedlet?y?=?20;</script> </body> </html>2)、const 聲明常量(只讀變量)
<!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><meta http-equiv="X-UA-Compatible" content="ie=edge"><title>Document</title> </head> <body><script>//const //const 只能聲明并賦值一次,否則會報錯。const?a?=?1;a?=?3;?//Uncaught?TypeError:?Assignment?to?constant?variable.</script> </body> </html>二、解構(gòu)表達式
? ?1)、數(shù)組解構(gòu)
<!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><meta http-equiv="X-UA-Compatible" content="ie=edge"><title>Document</title> </head> <body><script>// 數(shù)組解構(gòu)//題目一:打印arr數(shù)組元素//原始打印方式let arr?=?[1,2,3];let a = arr[0];let b = arr[1];let c = arr[2];console.log(a,b,c)//使用解構(gòu)表達式解構(gòu)數(shù)組,并打印let [a,b,c] = arr;console.log(a,b,c)</script> </body> </html>? ?2)、對象解構(gòu)
<!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><meta http-equiv="X-UA-Compatible" content="ie=edge"><title>Document</title> </head> <body><script>//題目二:聲明一個對象person,里面有三個元素,要求打印person內(nèi)部元素。const person = {name: "jack",age: 21,language: ['java', 'js', 'css']}//原始打印方式const?name?=?person.name;const?age?=?person.age;const?language?=?person.language;console.log(name, age, language)//使用解構(gòu)表達式解構(gòu)對象,并打印const { name, age, language } = person;console.log(name, age, language)</script> </body> </html>三、字符串處理
?1)、字符串擴展
<!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><meta http-equiv="X-UA-Compatible" content="ie=edge"><title>Document</title> </head> <body><script>//字符串擴展//startsWith():返回布爾值,表示參數(shù)字符串是否在原字符串的頭部//endsWith():返回布爾值,表示參數(shù)字符串是否在原字符串的尾部。//includes():返回布爾值,表示是否包含參數(shù)字符串。let str = "hello.vue";console.log(str.startsWith("hello"));//trueconsole.log(str.endsWith(".vue"));//trueconsole.log(str.includes("e"));//trueconsole.log(str.includes("hello"));//true</script> </body> </html>?2)、字符串模板
<!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><meta http-equiv="X-UA-Compatible" content="ie=edge"><title>Document</title> </head> <body><script>//字符串模板//1、模板字符串相當于加強版的字符串,可以用反引號`定義多行字符串,且還可以在字符串中加入變量和表達式。示例:let ss = `<div><span>hello?world ${20*10}<span></div>`;console.log(ss);//2、字符串插入變量和表達式。變量名寫在?${}?中,${}?中可以放入?JavaScript?表達式。function fun() {return "這是一個函數(shù)"}let info = `我是${name},今年${age + 10}了, 我想說: ${fun()}`;console.log(info);</script> </body> </html>瀏覽器控制臺打印效果:
四、函數(shù)優(yōu)化
? ?1)、函數(shù)參數(shù)默認值
<!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><meta http-equiv="X-UA-Compatible" content="ie=edge"><title>Document</title> </head> <body><script>//1)、函數(shù)參數(shù)默認值//要求:編寫一個函數(shù)計算“a + b”的和。//在ES6以前,我們無法給一個函數(shù)參數(shù)設(shè)置默認值,只能采用變通寫法:function add(a, b) {//?判斷b是否為空,為空就給默認值1b = b || 1;return a + b;}//?傳一個參數(shù)console.log(add(10)); // 11//現(xiàn)在可以這么寫:直接給參數(shù)寫上默認值,沒傳就會自動使用默認值function add2(a, b = 1) {return a + b;}console.log(add2(20)); // 21</script> </body> </html>? ?2)、不定參數(shù)
<!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><meta http-equiv="X-UA-Compatible" content="ie=edge"><title>Document</title> </head> <body><script>//2)、不定參數(shù)//不定參數(shù)用來表示不確定參數(shù)個數(shù),形如:...變量名,由...加上一個具名參數(shù)標識符組成。//具名參數(shù)只能放在參數(shù)列表的最后,并且有且只有一個不定參數(shù)。//要求:編寫一個fun函數(shù),功能如下:傳入N個參數(shù),輸出傳入的N個參數(shù)的數(shù)目。function fun(...values) {console.log(values.length)}fun(1, 2)??????//2fun(1, 2, 3, 4)??//4 </script> </body> </html>? ?3)、箭頭函數(shù)
<!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><meta http-equiv="X-UA-Compatible" content="ie=edge"><title>Document</title> </head> <body><script>//3)、箭頭函數(shù)(ES6中定義的簡寫方式)//① 一個參數(shù)時://要求:聲明一個參數(shù)的函數(shù)“print1”,并打印入?yún)ⅰ?/以前的方式:var?print1?=?function?(obj)?{console.log(obj); }print1("hello1");//hello1//現(xiàn)在,使用ES6箭頭函數(shù)的方式:var print2 = obj => console.log(obj);print2("hello2");//hello2//② 多個參數(shù)時://計算:a+b的和。//以前的方式:var sum1 = function (a, b) {return a + b;}console.log( sum1(11, 12) ); //23//現(xiàn)在,使用ES6箭頭函數(shù)的方式:var sum2 = (a, b) => a + b;console.log( sum2(11, 12) ); //23//計算:2a+b 的和//以前的方式:var sum3 = function (a, b) {c = a + b;return a + c;}console.log( sum3(10,20) );// 40var sum4 = (a, b) => {c = a + b;return a + c;}console.log( sum4(10, 20) ) // 40</script> </body> </html>? ?4)、實戰(zhàn):箭頭函數(shù)結(jié)合解構(gòu)表達式
<!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><meta http-equiv="X-UA-Compatible" content="ie=edge"><title>Document</title> </head> <body><script>//聲明一個person對象,打印nameconst person = {name: "jack",age: 21,language: ['java', 'js', 'css']}//以前的寫法:function?hello1(person)?{console.log("hello,"?+?person.name)}hello1(person);//hello,jack//現(xiàn)在,可以使用“箭頭函數(shù)+解構(gòu)”的方式簡化:var hello2 = ( {name} ) => console.log("hello,"?+ name);hello2(person); // hello,jack </script> </body> </html>五、對象優(yōu)化
? 1)、新增的API
<!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><meta http-equiv="X-UA-Compatible" content="ie=edge"><title>Document</title> </head> <body><script>//1)、新增的API(以下列舉常用的)const person = {name: "jack",age: 21,language: ['java', 'js', 'css']}//- Object.keys:方法用于獲取對象的所有key。console.log(Object.keys(person));//["name",?"age",?"language"]//- Object.values:方法用于獲取對象的所有value。console.log(Object.values(person));//["jack",?21,?Array(3)]//- Object.entries:方法用于獲取對象的所有entites。console.log(Object.entries(person));//[Array(2),?Array(2),?Array(2)]//- Object.assign // 方法用于將所有可枚舉屬性的值從一個或多個源對象復制到目標對象。它將返回目標對象。const target = { a: 1 };const source1 = { b: 2 };const source2 = { c: 3 };Object.assign(target, source1, source2);console.log(target);//{a:1,b:2,c:3}</script> </body> </html>? 2)、聲明對象簡寫
<!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><meta http-equiv="X-UA-Compatible" content="ie=edge"><title>Document</title> </head> <body><script>//2)、聲明對象簡寫const age = 23const name = "張三"//說明:這里的第一個age是屬性名,第二個age是屬性值const person1 = { age: age, name: name }console.log(person1);//{age: 23, name: "張三"}//如果屬性名和屬性值都一樣,就可以簡寫。const person2 = { age, name }console.log(person2);//{age: 23, name: "張三"}</script> </body> </html>? 3)、對象的函數(shù)屬性簡寫
<!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><meta http-equiv="X-UA-Compatible" content="ie=edge"><title>Document</title> </head> <body><script>//3)、對象的函數(shù)屬性簡寫let person3 = {name: "jack",//?以前:eat: function (food) {console.log(this.name + "在吃" + food);},//現(xiàn)在可以這樣:eat2(food) {console.log(this.name + "在吃" + food)},//甚至,可以使用箭頭函數(shù)簡寫eat3: food => console.log(person3.name + "在吃" + food),//注意:箭頭函數(shù) this 不能使用,否則獲取不到值,應該使用“對象.屬性”的方式。eat4: food => console.log(this.name + "在吃" + food)}person3.eat("香蕉");//jack在吃香蕉person3.eat2("蘋果")//jack在吃蘋果person3.eat3("橘子");//jack在吃橘子person3.eat4("菠蘿");//在吃菠蘿</script> </body> </html>? 4)、對象拓展運算符
<!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><meta http-equiv="X-UA-Compatible" content="ie=edge"><title>Document</title> </head> <body><script>//4)、對象拓展運算符//?1、拷貝對象(深拷貝)let p1 = { name: "Amy", age: 15 }//使用擴展運算符,“{...對象}"的方式拷貝對象let someone = { ...p1 }console.log(someone)??//{name:?"Amy",?age:?15}//?2、合并對象let age1 = { age: 15 }let name1 = { name: "Amy" }let p2 = { name: "zhangsan" }p2 = { ...age1, ...name1 }?//如果兩個對象的字段名重復,后面對象字段值會覆蓋前面對象的字段值console.log(p2)//{age: 15, name: "Amy"}</script> </body> </html>六、map 和 reduce 的使用
<!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><meta http-equiv="X-UA-Compatible" content="ie=edge"><title>Document</title> </head> <body><script>//數(shù)組中新增了map和reduce方法。//map():接收一個函數(shù),將原數(shù)組中的所有元素用這個函數(shù)處理后放入新數(shù)組返回。let arr = ['1', '20', '-5', '3'];//要求:將arr數(shù)組內(nèi)部的每個元素都乘以2,并返回。//第一種寫法: arr = arr.map((item) => {return item * 2});console.log(arr);//[2, 40, -10, 6]//更簡便的寫法:arr = arr.map(item => item * 2);console.log(arr);//[4, 80, -20, 12]//reduce():為數(shù)組中的每一個元素依次執(zhí)行回調(diào)函數(shù),不包括數(shù)組中被刪除或從未被賦值的元素,//語法: arr.reduce(callback,[initialValue])/**callback(執(zhí)行數(shù)組中每個值的函數(shù),包括四個參數(shù)),如下;1、previousValue (上一次調(diào)用回調(diào)返回的值,或者是提供的初始值(initialValue))2、currentValue (數(shù)組中當前被處理的元素)3、index (當前元素在數(shù)組中的索引)4、array (調(diào)用 reduce 的數(shù)組)*/let result = arr.reduce((a, b) => {console.log("上一次處理后:" + a);console.log("當前正在處理:" + b);return a + b;}, 100);console.log(result) //176</script> </body> </html>? 控制臺打印:?
七、Promise 編排
? 1)、前言
在JavaScript的世界中,所有代碼都是單線程執(zhí)行的。由于這個"缺陷”,導致JavaScript的所有網(wǎng)絡(luò)操作,瀏覽器事件,都必須是異步執(zhí)行。異步執(zhí)行可以用回調(diào)函數(shù)實現(xiàn)。一旦有一連串的ajax請求 a,bc,...后面的請求依賴前面的請求結(jié)果,就需要層層嵌套。這種縮進和層層嵌套的方式,非常容易造成上下文代碼混亂,我們不得不非常小心翼翼處理內(nèi)層函數(shù)與外層函數(shù)的數(shù)據(jù),一旦內(nèi)層函數(shù)使用了上層函數(shù)的變量,這種混亂程度就會加劇。總之,這種層疊上下文的層層嵌套方式,著實增加了神經(jīng)的緊張程度。因此,ES6 推出了 “Promise”對象。
? 2)、案例
實現(xiàn)功能:用戶登錄,并展示該用戶的各科成績,在頁面發(fā)送兩次請求。
- 查詢用戶,查詢成功說明可以登錄;
- 查詢用戶成功,則根據(jù)用戶id,查詢科目信息;
- 查詢科目成功,則根據(jù)科目id,獲取成績。
分析
此時后臺應該提供三個接口,一個提供用戶查詢接口,一個提供科目查詢接口,一個提供各科成績查詢接口,為了渲染方便,最好響應Json數(shù)據(jù)。在這里就不編寫后臺接口了,而是提供三個 json文件,直接提供json數(shù)據(jù),模擬后臺接口。
3)、Promise 創(chuàng)建
//要想創(chuàng)建一個 promise 對象、可以使用 new 來調(diào)用 Promise 的構(gòu)造器來進行實例化。 var promise = new Promise(function(resolve, reject) {// 異步處理// 處理結(jié)束后、調(diào)用resolve 或 reject });//Promise 構(gòu)造函數(shù)包含一個參數(shù)和一個帶有 resolve(解析)和 reject(拒絕)兩個參數(shù)的回調(diào)。在回調(diào)中執(zhí)行一些操作(例如異步),如果一切都正常,則調(diào)用 resolve,否則調(diào)用 reject。//對于已經(jīng)實例化過的 promise 對象可以調(diào)用 promise.then() 方法,傳遞 resolve 和 reject 方法作為回調(diào)。 promise.then(onFulfilled, onRejected) //promise簡化了對error的處理,上面的代碼我們也可以這樣寫: promise.then(onFulfilled).catch(onRejected)4)、Promise 改造以前嵌套方式
//1、查出當前用戶信息//2、按照當前用戶的id查出他的課程//3、按照當前課程id查出分數(shù)/* Promise 改造以前嵌套方式 : */ $.ajax({url: "mock/user.json",success(data) {console.log("查詢用戶:", data);$.ajax({url: `mock/user_corse_${data.id}.json`,success(data) {console.log("查詢到課程:", data);$.ajax({url: `mock/corse_score_${data.id}.json`,success(data) {console.log("查詢到分數(shù):", data);},error(error) {console.log("出現(xiàn)異常了:" + error);}});},error(error) {console.log("出現(xiàn)異常了:" + error);}});},error(error) {console.log("出現(xiàn)異常了:" + error);}});5)、使用Promise后的嵌套方式
/* 使用Promise后的嵌套方式(Promise可以封裝異步操作) */let p = new Promise((resolve, reject) => {//異步操作$.ajax({url: "mock/user.json",success: function (data) {console.log("查詢用戶成功:", data)resolve(data);},error: function (err) {reject(err);}});});p.then((obj) => {return new Promise((resolve, reject) => {$.ajax({url: `mock/user_corse_${obj.id}.json`,success: function (data) {console.log("查詢用戶課程成功:", data)resolve(data);},error: function (err) {reject(err)}});})}).then((data) => {console.log("上一步的結(jié)果", data)$.ajax({url: `mock/corse_score_${data.id}.json`,success: function (data) {console.log("查詢課程得分成功:", data)},error: function (err) {}});})6)、使用函數(shù)封裝請求,優(yōu)化處理后的方式
/* 使用函數(shù)封裝請求,優(yōu)化處理后的方式: */function get(url, data) {return new Promise((resolve, reject) => {$.ajax({url: url,data: data,success: data => {resolve(data);},error: err => {reject(err)}})});}get("mock/user.json").then((data) => {console.log("用戶查詢成功~~~:", data)return get(`mock/user_corse_${data.id}.json`);}).then((data) => {console.log("課程查詢成功~~~:", data)return get(`mock/corse_score_${data.id}.json`);}).then((data)=>{console.log("課程成績查詢成功~~~:", data)}).catch((err)=>{console.log("出現(xiàn)異常",err)});控制臺打印:
八、模塊化
1)、什么是模塊化?
模塊化就是把代碼進行拆分,方便重復利用,類似java中的導包,要使用一個包,必須先導包;
在 JS 中沒有包的概念,隨之而來的是 “模塊”。
模塊功能主要由兩個命令構(gòu)成:“export” 和“import”。
-
export 命令用于規(guī)定模塊的對外接口。
-
import 命令用于導入其他模塊提供的功能。
2)、export
新建 hello.js 文件
//`export`不僅可以導出對象,一切JS變量都可以導出。比如:基本類型變量、函數(shù)、數(shù)組、對象。/* 第一種寫法: */ //聲明util常量 const util = {sum(a, b) {return a + b;} } //導出 常量util export { util }/* 第二種寫法: */ //導出常量util export const util = {sum(a, b) {return a + b;} }/* 第三種寫法: */ //導出默認default,導入時可以任意定義名稱,比如叫:'util' export default {sum(a, b) {return a + b;} }新建 user.js文件
//`export`不僅可以導出對象,一切JS變量都可以導出。比如:基本類型變量、函數(shù)、數(shù)組、對象。 var?name?=?"jack" var?age?=?21 function add(a,b){return a + b; }export {name,age,add}3)、import
新建 main.js 文件
//導入 import util from "./hello.js" import {name,add} from "./user.js"//使用導入其他js文件的函數(shù)、對象 util.sum(1,2); console.log(name); add(1,3);參考資料:ES6 菜鳥教程
總結(jié)
以上是生活随笔為你收集整理的前端基础:学习 ES6 新特性的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: ZZULIOJ 1071:分解质因子
- 下一篇: 错误率_研究发现,商业语音识别系统存在高