不一樣與其餘遍歷數組的方法,
reduce
能夠返回任意的類型,更加的靈活。數組
Array.reduce(callback,starValue)
接受兩個參數,並返回一個最後的累加值(與starValue
同一類型)markdown
callback
:對數組每一個元素都執行的回調方法。函數
starValue
:初始值(能夠是任意類型)。this
callback(accumulator,current,currentInedex,arr)
接收四個參數:當前的累加結果、當前要累加的值、當前索引、數組自己spa
var total = [1, 2, 3].reduce(function (accumulator, current) {
return accumulator + current;
}, 0);
console.log(total) // 6
複製代碼
const arr = [
{
name: 'lgf',
age: 22
},
{
name: 'chm',
age: 22
},
{
name: 'lalal',
age: 21
}
]
var newArr = arr.reduce(function (accumulator, current) {
if (current.age === 22) {
accumulator.push(current.name);
}
return accumulator;
}, []);
console.log(newArr) // ["lgf", "chm"]
複製代碼
var nameList = arr.reduce(function (accumulator, current) {
if (current.age === 22) {
accumulator += '<li>' + current.name + '</li>';
}
return accumulator;
}, '');
console.log(nameList) // <li>lgf</li><li>chm</li>
複製代碼
var newArr = arr.reduce(function (accumulator, current) {
if (current.age === 22) {
const type = current.name
accumulator[type]=current.name;
}
return accumulator;
}, {});
console.log(newArr) // {lgf: "lgf", chm: "chm"}
複製代碼
Array.prototype.myReduce = function(fn, initialValue) {
// 由於是數組調用 myReduce方法因此this指向當前數組
// 初始化要返回累加值: 若是有傳初始值則acc的初始值爲initialValue,不然爲數組的第一個個值
let acc = initialValue || this[0]
// 定義開始計算的索引:若是有傳初始值則爲0,不然爲1
const startIndex = initialValue ? 0 : 1
// 遍歷數組 執行傳進來的函數(四個參數,前兩個是重點,1:當前累加總和,2:當前要累加的值,3:當前要累加值的索引,4:當前的數組)
for (let i = startIndex; i < this.length; i++) {
acc = fn(acc, this[i], i, this)
}
// 返回累加值
return acc
}
複製代碼
判斷參數是否合法:prototype
Array.protopy.myReduce = function(fn,value){
if(typeof fn !== 'function'){
console.log('第一個參數必須爲一個函數')
return
}
const acc = value || this[0];
const startIndex = value ? 0 : 1
for(let i = startIndex; this.length,i++){
acc = fn(acc, this[i], i, this)
}
return acc
}
複製代碼