一、變量解構賦值的用途
1)交換變量的值
let x = 1;let y = 2;[x, y] = [y, x]
2)從函數返回多個值
// 返回一個數組function example(){ return [1, 2, 4];}let [a, b, c] = example() // 返回一個對象function example(){ return { foo:1, bar: 2 }}let {foo, bar} = example(); 或者 ( {foo, bar} = example() )
3)提取JSON數據
let jsonData = { id:42, status: "OK", data: [867, 5309]};let { id, status, data: number} = jsonData;
4)輸入模塊的指定方法
加載模塊時,往往需要指定輸入的方法,解構賦值使得輸入語句非常清晰
const { SourceMapConsumer, SourceNode } = require("source-map")
5) 數組復制的功能
在es5中,開發者經常使用 concat() 方法克隆數組:
// 在 es5 中克隆數組var colors = [ 'red', 'green', 'blue' ];var clonedColors = colors.concat();console.log(clonedColors); // "[red, green, blue]"
concat() 方法的設計初衷是連接兩個數組,如果調用時不傳遞參數就會返回當前數組的副本。在es6中可以通過不定元素的語法來實現相同的目標:
let colors = [ 'red', 'green', 'blue' ]let [ ...clonedColors ] = colors;console.log(clonedColors); // "[red, green, blue]"
6) 結合Set集合,創建一個無重復元素的數組
function eliminateDuplicates(items) { return [...new Set(items)]}let numbers = [1, 2, 3, 3, 3, 4, 5];let noDuplicates = eliminateDuplicates(numbers );console.log(noDuplicates ); // [1,2,3,4,5]
7) 使用apply 把兩個數據合并成一個
var arra1 = [{ name: '小智', age: 26}]var arra2 = [{ name: '大智', age: 27}]arra1.push.apply(arra1, arra2)console.log(arra1)
二、函數的用處(常見就不多說了)
1)創建立即執行函數表達式
// es5let person = function(name) { return { getName: function() { return name; } }}('小智');console.log(person.getName()); // 小智
在這段代碼中,立即執行函數表達式創建了一個包含getName() 方法的新對象,將參數 name 作為該對象的一個私有成員返回給函數的調用者。
只要箭頭函數包裹在小括號里,就可以用它實現相同的功能
// es6let person = ((name) => { return { getName: function() { return name; } }})('小智2');console.log(person.getName()); //小智
2.利用參數默認值可以指定某一個參數不得省略,如果省略就拋出一個錯誤。
function throwEmptyError() { throw new Error('參數不能為空');}function foo(mustBeParams = throwEmptyError() ){ return mustBeParams();}foo() // 參數不能為空
三、擴展對象的功能性讓代碼更加簡潔
1) 可計算屬性名
在es6中,使用方括號可以計算屬性名稱,如
let lastName ='last name';let person = { "first name": 'Nicholas', [lastName]: 'Zakas'}console.log(person['first name']); // "Nicholas"console.log(person[lastName]); // Zakas
2) 利用 Object.assign()合并兩個對象
function request(options) { let defaultOptions = { port: 8000, type: 'get' } Object.assign(options,defaultOptions); console.log(options)}request({url: 'http://www.baidu.com'})
四、結合es6簡潔函數寫法,高階函數的應用
1) tab 函數
// 此處tap函數接受一個 vaule 并返回一個包含value 閉包函數,該函數被執行const tap = (value) => (fn) => ( typeof(fn) === 'function' && fn(value), console.log(value))
tab函數用處:假設你在遍歷一個來自服務器的數組,并發現數據錯了,因此你想調試一下,看看數組包含了什么,就可以用 tab函數
[1, 2 ,3, 4].forEach((a) => { tap(a)((a)=> { console.log(a) })});#### 2) once 函數
在很多情況下,我們只需要運行一次給定的函數,發起一次銀行支付請求等,這時就可以用到 once 函數。
const once = (fn) => { let done = false; return function () { return done?undefined:((done=true),fn.apply(this,arguments)) }}const doPayment = once(()=>{ console.log('payment is done')})doPayment(); // payment is doneconsole.log(doPayment()); //undefined#### 3) 函數柯里化的應用
開發者編寫代碼的時候應用的不同階級編寫很多日志,我們可以編寫一個如下的日志函數:
const loggerHelper = (mode, initialMessage, errorMessage, lineNo) => { if (mode === 'DEBUG') { console.debug(initialMessage,errorMessage + 'at line:' + lineNo) } else if (mode === 'ERROR') { console.error(initialMessage,errorMessage + 'at line:' + lineNo) } else if (mode === 'WARN') { console.warn(initialMessage,errorMessage + 'at line:' + lineNo) } else throw "Wrong mode"}
當開發者需要向控制臺打印Stats.js文件中的錯誤時,可以用如下方式:
loggerHelper("ERROR", "ERROR At Stats.js", "Invalid argument passed", 23);
這樣對于 我們追求完美可讀的程序員來說,可能是不太能接受的,現在用柯里來優化以上代碼,
先簡要說明什么是函數柯里化:
柯里化是把一個多參數函數轉換成一個嵌套的一元函數過程。
封裝一個把把多參數函數轉制為一元函數的curry函數
let curry = (fn) => { if (typeof fn !== 'function') { throw Error('No function provided'); } return function curriedFn(...args) { // 傳入參數是否小于函數參數列表長度, if (args.length < fn.length) { return function() { return curriedFn.apply(null, args.concat([].slice.call(arguments))); } } return fn.apply(null, args) }} let errorLogger = curry(loggerHelper)("ERROR")("ERROR At Stats.js");let debugLogger = curry(loggerHelper)("DEBUG")("ERROR")("Debug At Stats.js");let warnLogger = curry(loggerHelper)("WARN")("Warn")("At Stats.js");// 用于錯誤errorLogger("Error message", 21)// 用于調試debugLogger('Debug message', 233)// 用于警告warnLogger("Warn message", 34);
現在我們能夠輕松引用上面的柯里化并在各自的上下文中使用它們了。
總結
以上所述是小編給大家介紹的ES6 中可以提升幸福度的小功能,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對武林網網站的支持!
新聞熱點
疑難解答