關于前端JavaScript ES6詳情
1、簡介
ES6
是一個泛指,含義是 5.1 版以后的 JavaScript
的下一代標準,涵蓋了 ES2015
、ES2016
、ES2017
語法標準。
ES6
新特性目前只有在一些較新版本瀏覽器得到支持,老版本瀏覽器里面運行我們需要將ES6轉換為ES5。
Chrome
:51 版起便可以支持 97% 的 ES6 新特性。Firefox
:53 版起便可以支持 97% 的 ES6 新特性。Safari
:10 版起便可以支持 99% 的 ES6 新特性。IE
:Edge 15可以支持 96% 的 ES6 新特性。Edge 14 可以支持 93% 的 ES6 新特性。(IE7~11 基本不支持 ES6)
1.1 Babel 轉碼器
它是一個廣泛使用的 ES6 轉碼器。
npm install --save-dev @babel/core
配置文件.babelrc
# 最新轉碼規(guī)則 $ npm install --save-dev @babel/preset-env # react 轉碼規(guī)則 $ npm install --save-dev @babel/preset-react // `presets`字段設定轉碼規(guī)則,官方提供以下的規(guī)則集,你可以根據(jù)需要安裝。 { "presets": [ "@babel/env", "@babel/preset-react" ], "plugins": [] }
1.2 polyfill
Babel
默認只是對JavaScript
新語法進行了轉換,為了支持新API還需要使用polyfill
為當前環(huán)境提供一個墊片(也就是以前的版本沒有,打個補?。?。
比如:core-js
和regenerator-runtime
$ npm install --save-dev core-js regenerator-runtime import 'core-js'; import 'regenerator-runtime/runtime';
2、let 和 const
2.1 let
就作用域來說,ES5
只有全局作用域和函數(shù)作用域。使用let
聲明的變量只在所在的代碼塊內(nèi)有效。
if(true){ let a = 1; var b = 2 } console.log(a)// ReferenceError: a is not defined console.log(b)// 2
看下面的例子,我們預期應該輸出1,因為全局只有一個變量i,所以for
執(zhí)行完后,i=5
,函數(shù)打印的值始終是5。
var funcs = []; for (var i = 0; i < 5; i++) { funcs.push(function () { console.log(i); }); } funcs[1](); // 5
修復,將每一次迭代的i變量使用local存儲,并使用閉包將作用域封閉。
var funcs = []; for (var i = 0; i < 5; i++) { (function () { var local = i funcs.push(function () { console.log(local); }); } )() } funcs[1](); // 1
使用let
聲明變量i也可以達到同樣的效果。
2.2 const
const
用于聲明一個只讀的常量。必須初始化,一旦賦值后不能修改。const
聲明的變量同樣具有塊作用域。
if (true) { const PI = 3.141515926; PI = 66666 // TypeError: Assignment to constant variable. } console.log(PI) // ReferenceError: PI is not defined
const
聲明對象
const obj = {}; // 為 obj 添加一個屬性,可以成功 obj.name = 'hello'; // 將 obj 指向另一個對象,就會報錯 obj = {}; // TypeError: "obj" is read-only
3、解構
解構字面理解是分解結構,即會打破原有結構。
3.1 對象解構
基本用法:
let { name, age } = { name: "hello", age: 12 }; console.log(name, age) // hello 12
設置默認值
let { name = 'hi', age = 12 } = { name : 'hello' }; console.log(name, age) // hello 12
rest
參數(shù)(形式為...變量名)可以從一個對象中選擇任意數(shù)量的元素,也可以獲取剩余元素組成的對象。
let { name, ...remaining } = { name: "hello", age: 12, gender: '男' }; console.log(name, remaining) // hello {age: 12, gender: '男'}
3.2 數(shù)組解構
rest
參數(shù)(形式為...變量名)從數(shù)組中選擇任意數(shù)量的元素,也可以獲取剩余元素組成的一個數(shù)組。
let [a, ...remaining] = [1, 2, 3, 4]; console.log(a, remaining) // 1 [2, 3, 4]
數(shù)組解構中忽略某些成員。
let [a, , ...remaining] = [1, 2, 3, 4]; console.log(a, remaining) // 1 [3, 4]
3.3 函數(shù)參數(shù)解構
數(shù)組參數(shù)
function add([x, y]){ return x + y; } add([1, 2]); // 3
對象參數(shù)
function add({x, y} = { x: 0, y: 0 }) { return x + y; } add({x:1 ,y : 2});
3.4 常見場景
在不使用第三個變量前提下,交換變量。
let x = 1; let y = 2; [x, y] = [y, x];
提取JSON數(shù)據(jù)
let json = { code: 0, data: {name: 'hi'} }; let { code, data: user } = json; console.log(code, user); // 0 {name: 'hi'}
遍歷Map結構
const map = new Map(); map.set('name', 'hello'); map.set('age', 12); for (let [key, value] of map) { console.log(key + " is " + value); }
4、擴展
4.1 字符串擴展
模版字符串,這個很有用。使用反引號(`)標識。它可以當作普通字符串使用,也可以用來定義多行字符串,或者在字符串中嵌入變量。
`User ${user.name} is login...`);
4.2 函數(shù)擴展
ES6
允許為函數(shù)的參數(shù)設置默認值,即直接寫在參數(shù)定義的后面。
一旦設置了參數(shù)的默認值,函數(shù)進行聲明初始化時,參數(shù)會形成一個單獨的作用域(context
)。等到初始化結束,這個作用域就會消失。這種語法行為,在不設置參數(shù)默認值時,是不會出現(xiàn)的。
function add(x, y = 1) { return x + y }
替代apply()寫法
// ES5 的寫法 Math.max.apply(null, [1, 3, 2]) // ES6 的寫法 Math.max(...[1, 3, 2])
4.3 數(shù)組擴展
合并數(shù)組
// ES5 的寫法 var list = [1,2] list = list.concat([3]) // ES6 的寫法 var list = [1,2] list = [...list, 3]
數(shù)組新API
Array.from(),Array.of(),find() 和 findIndex()等,參考MDN
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array
4.4 對象擴展
對象屬性,方法簡寫
data = [1,2] const resp = {data}; // 屬性簡寫,等同于 {data: data} const obj = { add(x, y) { // 方法簡寫,等同于 add: function(x, y){...} return x + y; } };
擴展屬性
const point = {x: 1, y: 2} const pointD = {...point, z: 3} console.log(pointD) // {x: 1, y: 2, z: 3} // 當有重復屬性時,注意順序問題。 const point = {x: 1, y: 2} const pointD = {...point, x: 4, z: 3} console.log(pointD) // {x: 4, y: 2, z: 3} const point = {x: 1, y: 2} const pointD = {x: 4, z: 3, ...point} console.log(pointD) // {x: 1, z: 3, y: 2}
屬性的描述對象
對象的每個屬性都有一個描述對象(Descriptor
),用來控制該屬性的行為。
const point = {x: 1, y: 2} Object.getOwnPropertyDescriptor(point, 'x') /** { configurable: true enumerable: true // 表示可枚舉 value: 1 writable: true // 表示可寫 } **/
屬性的遍歷
for...in
循環(huán):只遍歷對象自身的和繼承的可枚舉的屬性。Object.keys()
:返回對象自身的所有可枚舉的屬性的鍵名。JSON.stringify()
:只串行化對象自身的可枚舉的屬性。Object.assign()
: 忽略enumerable
為false
的屬性,只拷貝對象自身的可枚舉的屬性。
const point = {x: 1, y: 2} for(let key in point){ console.log(key) }
對象新增的一些方法:Object.assign()
Object.assign()
方法實行的是淺拷貝,而不是深拷貝。也就是說,如果源對象某個屬性的值是對象,那么目標對象拷貝得到的是這個對象的引用。常見用途:
克隆對象
function clone(origin) { return Object.assign({}, origin); }
合并對象
const merge = (target, ...sources) => Object.assign(target, ...sources);
指定默認值
const DEFAULT_CONFIG = { debug: true, }; function process(options) { options = Object.assign({}, DEFAULT_CONFIG, options); console.log(options); // ... }
4.5 運算符擴展
指數(shù)運算符
2 ** 10 // 1024 2 ** 3 ** 2 // 512 相當于 2 ** (3 ** 2) let a=10; a **= 3; // 相當于 a = a * a * a
鏈判斷運算符
obj?.prop
判斷對象屬性是否存在,func?.(...args)
函數(shù)或?qū)ο蠓椒ㄊ欠翊嬖凇?/p>
const obj = {name: 'job', say(){console.log('hello')}} obj?.name // 等于 obj == null ? undefined : obj.name obj?.say() // 等于 obj == null ? undefined : obj.say()
空判斷運算符
JavaScript
里我們用||運算符指定默認值。 當我們希望左邊是null
和undefined
時才觸發(fā)默認值時,使用??。
const obj = {name: ''} obj.name || 'hello' // 'hello' obj.name ?? 'hello' // ''
5、for…of
因為for...in
循環(huán)主要是為遍歷對象而設計的,因為數(shù)組的鍵名是數(shù)字,所以遍歷數(shù)組時候它返回的是數(shù)字,很明顯這不能滿足開發(fā)需求,使用for...of
可以解決這個問題。
const list = ['a', 'b', 'c'] for (let v in list){ console.log(v) // 0,1,2 } for (let v of list){ console.log(v) // a,b,c }
6、小結
到此這篇關于關于前端JavaScript ES6詳情的文章就介紹到這了,更多相關JavaScript ES6
內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
國慶節(jié)到了,利用JS實現(xiàn)一個生成國慶風頭像的小工具 詳解實現(xiàn)過程
明天就是國慶節(jié)了,最近看到好多好友換了國慶風的頭像,感覺這個挺有意思,就找到了類似的源碼研究了一番,并進行了改造(并非原創(chuàng),只是進行了改造,只要想分享一下實現(xiàn)思路)。下面就來看看如何實現(xiàn)一鍵生成國慶風頭像小工具。​2021-09-09