谁能告诉我关于使用点差减少
var arr = [10,10, 8000, 8000, 2, 17]
var unique = arr.reduce((x, y) => x.includes(y) ? x : [...x, y], []);
console.log(unique)
x
在该范围内做什么?而spread syntax
也呢?和最后一个空数组[ ]
当我console.log x时,它仅显示第一个值数组,而x则显示数组中的其余值
答案 0 :(得分:1)
为此,您需要了解reduce函数的工作方式。它需要2个参数:一个函数和累加器的初始值。
(x, y) => x.includes(y) ? x : [...x, y]
这是一个函数,在reduce调用内部调用。对于x,传递累加器,对于y,数组的当前值。因此,此函数获取累加器和当前值,检查该值是否已在累加器中(通过使用include)。如果是函数,则返回累加器x,但是如果y不在x中,则函数为累加器返回一个新数组,其中包含旧累加器的所有元素和新值x。
到目前为止,这不是从数组中删除重复项的最佳方法,因为您搜索整个数组的每个循环。如果您需要一个没有重复项的数组,请考虑使用Sets。
答案 1 :(得分:0)
传递给reduce的第一个参数是回调函数。
它有两个参数累加器(在这种情况下为x)和currentValue(在这种情况下为y)
Reduce将遍历数组。在每次运行时,返回的值都是累加器的新值,currentValue是当前迭代中的元素,因此第一次迭代将是10。
第二个参数(还有其他参数,在这种情况下)是 累加器,在这种情况下为空数组。如果没有提供默认值的数组,则会出现问题,因为在没有提供默认值的情况下,数组的第一个元素将用作初始累加器值,因此我们无法将其追加到数字上。
为了提供更多的清晰度,我将进一步扩展代码
var arr = [10,10, 8000, 8000, 2, 17]
var unique = arr.reduce((x, y) => {
// does the array x include the value y
if(x.includes(y){
// We want an array with no duplicates, so we don't append y to the array, by
// simply returning x
return x;
}
// if we made it hear it must mean y is unique value so we want to add it to the
// array, so we want to return x with y include. We don't want to mutate x, so
// return a new array with all the elements of x and y at the end
// we do this using the spread operator(...) it will copy all elements of x into
// the new array
return [...x, y]
}, []);
console.log(unique)
答案 2 :(得分:-1)
也许使用不同的变量名会有所帮助:
var arr = [10,10, 8000, 8000, 2, 17];
var initialiser = [];
var unique = arr.reduce((output, currentElement) => {
// If our output array includes the current element
if (output.includes(currentElement)) {
// Return the output without adding to it
return output;
} else {
// Otherwise create a new array by spreading out
// the elements of the output array, and adding the
// current element.
// `return output.concat(currentElement);` would
// give the same result
return [...output, currentElement];
}
// Pass in the initialiser object which
// we call `output` in each iteration
}, initialiser);
答案 3 :(得分:-1)
像这样:
Array.prototype.reduce = function(callback, value) {
let result;
// initial index
let initialIndex = 0;
// initial value
let initialValue = this[0];
// If there is a second parameter
if (typeof value !== undefined) {
initialIndex = 1;
initialValue = value;
}
// Assignment initial value
result = initialValue;
// Traversing
for (var i = initialIndex; i < this.length; i++) {
// your callback and x,y here
result = callback(result, this[i]);
}
// Return a new value
return result;
};