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

Ste*_*tta 2 javascript reduce functional-programming this

我正在学习 练习 16 中关于Javascript 函数式编程的在线课程,它向您展示了 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];
	}
};
Run Code Online (Sandbox Code Playgroud)

我不明白第一个 if 语句,当它检查this.length这实际上意味着什么时?

请注意,这与 ES5 中的 reduce 不同,它返回一个值而不是一个数组,这仅用作学习目的的示例。

Jam*_*rpe 5

Array.prototype.reduce = function(...
Run Code Online (Sandbox Code Playgroud)

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

[1, 2, 3].reduce(...
Run Code Online (Sandbox Code Playgroud)

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

[].reduce(...
Run Code Online (Sandbox Code Playgroud)

基于评论:

如果数组为空,则什么都不做

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


正如@Alnitak 在评论中指出的那样,reduce规范相比,这种实现是有缺陷MDN上提供了一种不同的实现用于填充旧浏览器。