ES6 之reduce的高階技巧

2022-07-06 19:15:10 字數 1222 閱讀 4964

reduce() 方法接收乙個函式作為累加器,陣列中的每個值(從左到右)開始縮減,最終計算為乙個值。reduce() 方法接受四個引數:初始值(或者上一次**函式的返回值),當前元素值,當前索引,呼叫 reduce() 的陣列。

reduce() 的幾個強大用法:

var total = [ 0, 1, 2, 3 ].reduce(( acc, cur ) => , 0);

console.log(total) // 6

var array = [[1, 2], [3, 4], [5, 6]].reduce(( acc, cur ) => , );

console.log(array) // [ 0, 1, 3, 4, 5, 6 ]

let names = ['tom', 'jim', 'jack', 'tom', 'jack'];

const countnames = names.reduce((allnames, name) =>

else

return allnames;

}, {});

console.log(countnames) //

const arraysum = (arr, val) => arr.reduce((acc, cur) => , 0);

let arr = [ 0, 1, 3, 0, 2, 0, 2, 3 ]

console.log(arraysum(arr, 0)) // 陣列arr中 0 元素出現的次數為3

let arr = [1, 2, 1, 2, 3, 5, 4, 5, 3, 4, 4, 4, 4];

let result = arr.sort().reduce((init, current) =>

return init;

}, );

console.log(result); //[1,2,3,4,5]

當然,對於陣列去重,也可以直接使用es6的…[拓展運算子] + set 實現:

// console.log(...new set([1,2,3,4,5,2,4,1]))

const dedupe = (array) =>

console.log(dedupe([1, 1, 2, 3])) //[1,2,3]

es6中reduce的用法 Es6基礎語法

1 this this代表當前正在執行的物件 function fn fn window const obj new fn fn.call 2 箭頭函式 1 箭頭函式的this是在定義的時候就固定不變了 2 箭頭函式 沒有自己的this 3 箭頭函式 不能當類 構造器 使用 不可以 new 4 箭頭...

ES6 新特性 map 和 reduce

陣列中新增了 map 和 reduce 方法。接收乙個函式,將原陣列中的所有元素用這個函式處理後放入新陣列返回。語法 arr.reduce callback,initialvalue reduce 為陣列中的每乙個元素依次執行 函式,不包括陣列中被刪除或從未被賦值的元 素,接受四個引數 1 prev...

ES6 細化ES6之 物件的擴充套件

物件的屬性 屬性表示法es6 允許在大括號裡面,直接寫入變數和函式,作為物件的屬性和方法 es5 let name 張無忌 function sayme es5定義物件的屬性和方法的方式 var obj console.log obj.name 張無忌es6 let name 張無忌 functio...