作者热门文章
- xml - AJAX/Jquery XML 解析
- 具有多重继承的 XML 模式
- .net - 枚举序列化 Json 与 XML
- XML 简单类型、简单内容、复杂类型、复杂内容
我正在努力创建自己的回调函数和高阶函数组。我坚持复制下划线减少功能或 ._reduce 功能。有人可以帮助我了解它是如何在引擎盖下工作的,这对我来说已经有几天了,我很困惑。这是我到目前为止所拥有的。请理解我没有使用下划线库,我正在尝试复制它以便我可以进一步了解高阶函数。谢谢。
var reduce = function(collection, iterator, accumulator) {
var iterator = function(startPoint, combiner){
for(var i = 0; i <combiner.length; i++){
startPoint += combiner[i];
}
return iterator(accumulator, collection);
}
最佳答案
一个简单的递归函数就可以了
// arr - some array of values
// f - the reducing function
// acc - initial value for the accumulator
function reduce(arr, f, acc) {
if (arr.length === 0)
return acc
else
return reduce(arr.slice(1), f, f(acc, arr[0]))
}
// --------------------------------------------------
// example 1:
// reduce an array of numbers using an adding function
var ex1 = reduce([1,2,3], function(acc, x) { return acc + x }, 0)
console.log(ex1)
//=> 6
// --------------------------------------------------
// example 2:
// reduce an array of pairs to a mapping object
var ex2 = reduce([['a', 1], ['b', 2], ['c', 3]], function(acc, pair) {
var key = pair[0]
var value = pair[1]
acc[key] = value
return acc
}, {})
console.log(ex2)
//=> { a: 1, b: 2, c: 3 }
正如@torazaburo 在评论中指出的那样,如果您可以使用 ES6,解构赋值将进一步清理实现
// ES6
function reduce([x, ...xs], f, acc) {
if (x === undefined)
return acc
else
return reduce(xs, f, f(acc, x))
}
或者用箭头函数让它变得 super 甜
// ES6, same as above but using arrow function and ternary expression
const reduce = ([x, ...xs], f, acc)=>
x === undefined ? acc : reduce(xs, f, f(acc, x))
Underscore 实现确实提供了一些其他便利,但我猜这些是为了保持与原生 Array.prototype.reduce 的兼容性。 .我个人不会以这种方式实现 reduce,但这不是重点。
这是支持这些其他功能的修改后的实现
// our reduce version 2.0
function reduce(collection, iterator, memo, context) {
function loop(memo, i) {
if (collection.length === i)
return memo
else
return loop(iterator.call(context, memo, collection[i], i, collection), i + 1)
}
return loop(memo, 0)
}
您可以像上面一样使用它,只是现在它为回调提供了更多信息
注意
我有目的地决定不实现 Underscore 的 reduce 行为,该行为允许您在没有初始值的情况下执行归约。支持这种行为会导致代码不安全,并且一开始就不应该将其放入 Underscore 中。
关于javascript - 从头开始创建下划线 reduce 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38087989/
我需要用这样的数据构建一个表: ┌────────┬───────────┬────────┐ │ ID │ Name │ Age │ ├────
我是一名优秀的程序员,十分优秀!