javascript - check for this.length into a function 是什么意思?

标签 javascript functional-programming this reduce

我正在学习关于 Javascript Functional Programming 的在线类(class) 在练习 16 中,它向您展示了 reduce 是如何实际实现的,以帮助您理解如何使用它,但是在这个实现中有一些我实际上没有得到的东西,我将展示代码:

Array.prototype.reduce = function(combiner, initialValue) {
	var counter, accumulatedValue;

	// If the array is empty, do nothing
	if (this.length === 0) {
		return this;
	}
	else {
		// If the user didn't pass an initial value, use the first item.
		if (arguments.length === 1) {
			counter = 1;
			accumulatedValue = this[0];
		}
		else if (arguments.length >= 2) {
			counter = 0;
			accumulatedValue = initialValue;
		}
		else {
			throw "Invalid arguments.";
		}

		// Loop through the array, feeding the current value and the result of
		// the previous computation back into the combiner function until
		// we've exhausted the entire array and are left with only one value.
		while(counter < this.length) {
			accumulatedValue = combiner(accumulatedValue, this[counter])
			counter++;
		}

		return [accumulatedValue];
	}
};

我不明白第一个 if 语句,当它检查 this.length 时,这到底是什么意思?

Take note this is different from the reduce in ES5, which returns an value instead of an Array, this is used just as a sample for the learning purpose.

最佳答案

Array.prototype.reduce = function(...

是说,“在 Array 的原型(prototype)上创建一个函数”——这意味着新的 reduce 函数将可以在所有数组上调用,例如:

[1, 2, 3].reduce(...

这意味着您也可以在空数组上调用它,例如:

[].reduce(...

基于评论:

If the array is empty, do nothing

您正在处理一个数组,当函数被调用时,this 被设置为调用 reduce 的数组。 reduce 的实现假定如果该数组为空(即 this.length === 0),您不能在逻辑上进一步减少它 - 没有什么可以减少,因此您可以返回相同的空数组。


正如@Alnitak 在评论中指出的那样,与the specification 相比,reduce 的这种实现存在缺陷。 . the MDN 上提供了不同的实现用于填充旧浏览器。

关于javascript - check for this.length into a function 是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34595902/

相关文章:

javascript - 如何在回调中访问正确的“this”?

javascript - 使用 JavaScript 的动态表生成器

javascript - 带有 svg 和(双击)单击事件的 <object> 标签

C# FP : Validation and execution with error handling functional way - space for improvement?

collections - Kotlin:将对象列表映射到一个字段中的值列表的惯用方式?

Scala:Function0 与按名称参数

javascript - 将对象绑定(bind)到 Promise.then() 参数的正确方法

javascript - odoo 10 - "Overwriting"来自旧模块的 Javascript 代码

javascript - 如何设计 JavaScript

javascript - 在没有 "this"的情况下访问 JavaScript 中对象中的变量