Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

【JavaScript】Reducer #22

Open
swiftwind0405 opened this issue Mar 5, 2020 · 0 comments
Open

【JavaScript】Reducer #22

swiftwind0405 opened this issue Mar 5, 2020 · 0 comments

Comments

@swiftwind0405
Copy link
Owner

swiftwind0405 commented Mar 5, 2020

reducer 是什么

要理解 reducer 的第一点也是最重要的一点是它永远返回一个值,这个值可以是数字、字符串、数组或对象,但它始终只能是一个。reducer 对于很多场景都很适用,但是它们对于将一种逻辑应用到一组值中并最终得到一个单一结果的情况特别适用。

另外需要说明:reducer 本质上不会改变你的初始值;相反,它们会返回一些其他的东西。

语法:

arr.reduce(callback( accumulator, currentValue[, index[, array]] )[, initialValue])

示例

有多少个 X

假设您有一个数字数组,并且希望返回一个报告这些数字在数组中出现的次数的对象。请注意,这同样适用于字符串。

const nums = [3, 5, 6, 82, 1, 4, 3, 5, 82];

const result = nums.reduce((tally, amt) => {
    tally[amt] ? tally[amt]++ : tally[amt] = 1;
    return tally;
}, {});

console.log(result);
//{ '1': 1, '3': 2, '4': 1, '5': 2, '6': 1, '82': 2 }

最初,我们有一个数组和将要放入其中的对象。在 reducer 中,我们首先判断这个item是否存在于累加器中,如果是存在,加1。如果不存在,添加这一项并设置为1。最后,请返回每一项出现的次数。然后,我们运行reduce函数,同时传递 reducer 和初始值。

获取一个数组并将其转换为显示某些条件的对象

假设我们有一个数组,我们希望基于一组条件创建一个对象。reduce 在这里非常适用!现在,我们希望从数组中任意一个数字项创建一个对象,并同时显示该数字的奇数和偶数版本。

const nums = [3, 5, 6, 82, 1, 4, 3, 5, 82];

// we're going to make an object from an even and odd
// version of each instance of a number
const result = nums.reduce((acc, item) => {
  acc[item] = {
    odd: item % 2 ? item : item - 1,
    even: item % 2 ? item + 1 : item
  }
  return acc;
}, {});

console.log(result);

控制台输出结果:

{ 
	'1': { odd: 1, even: 2 },
	'3': { odd: 3, even: 4 },
	'4': { odd: 3, even: 4 },
	'5': { odd: 5, even: 6 },
	'6': { odd: 5, even: 6 },
	'82': { odd: 81, even: 82 } 
}

当我们遍历数组中的每一项时,我们为偶数和奇数创建一个属性,并且基于一个带模数运算符的内联条件,我们要么存储该数字,要么将其递增1。模算符非常适合这样做,因为它可以快速检查偶数或奇数 —— 如果它可以被2整除,它是偶数,如果不是,它是奇数。

找最大值

const vals = [5, 4, 9, 2, 1];
const biggest = vals.reduce((acc, val) => {
  if (val > acc) {
    acc = val;
  }
  return acc;
});
console.log(biggest);

优化精简一下:

const vals = [5, 4, 9, 2, 1];
const biggest = vals.reduce((a, b) => a > b ? a : b);
console.log(biggest);

.reduce() 代替 .filter() .map()

const numbers = [-5, 6, 2, 0,];
const doubledPositiveNumbers = numbers.reduce((accumulator, currentValue) => {
  if (currentValue > 0) {
    const doubled = currentValue * 2;
    accumulator.push(doubled);
  }
  return accumulator;
}, []);
console.log(doubledPositiveNumbers); // [12, 4]

数组去重

const array = ['a', 'b', 'a', 'b', 'c', 'e', 'e', 'c', 'd', 'd', 'd', 'd']
const orderedArray = array.reduce((acc, cur) => acc.indexOf(cur) === -1 ? acc.push(cur) : acc, [])
console.log(orderedArray);

二维数组拍平

const flattened = [[0 ,1], [2, 3], [4, 5]].reduce((acc, cur) => acc.concat(cur), []);

用 reduce 实现 map

if (!Array.prototype.mapUsingReduce) {
  Array.prototype.mapUsingReduce = function(callback, thisArg) {
    return this.reduce(function(mappedArray, currentValue, index, array) {
      mappedArray[index] = callback.call(thisArg, currentValue, index, array)
      return mappedArray
    }, [])
  }
}

[1, 2, , 3].mapUsingReduce(
  (currentValue, index, array) => currentValue + index + array.length
) // [5, 7, , 10]

参考文档

@swiftwind0405 swiftwind0405 changed the title useRef 【Day24】浏览器的渲染流程 Mar 16, 2020
@swiftwind0405 swiftwind0405 changed the title 【Day24】浏览器的渲染流程 【Day24】Reducer Apr 27, 2020
@swiftwind0405 swiftwind0405 changed the title 【Day24】Reducer 【JavaScript】Reducer Apr 29, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant