<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<meta name="author" content="杨欣">
<title>reduce</title>
</head>
<body>
<script>
Array.prototype.my_reduce = function (callback, initialValue) {
if (!Array.isArray(this) || !this.length || typeof callback !== 'function') {
return []
} else {
// 判断是否有初始值
let hasInitialValue = initialValue !== undefined;
let value = hasInitialValue ? initialValue : tihs[0];
for (let index = hasInitialValue ? 0 : 1; index < this.length; index++) {
const element = this[index];
value = callback(value, element, index, this)
}
return value
}
}
let arr = [1, 2, 3, 4, 5]
let res = arr.my_reduce((pre, cur, i, arr) => {
console.log(pre, cur, i, arr)
return pre + cur
}, 10)
console.log(res)//25
</script>
</body>
</html>
原文:https://www.cnblogs.com/samsara-yx/p/12212936.html