一、變量解構賦值的用途
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() // 參數不能為空三、擴展對象的功能性讓代碼更加簡潔
新聞熱點
疑難解答
圖片精選