ES6中关于reduce、set和数组重构

2 篇文章 0 订阅

1、数组的 reduce方法

1)使用deduce代替map+ filter

要把数组中的值进行计算后再滤掉一些值,然后输出新数组。一般我们使用 map 和 filter 方法组合来达到这个目的,但这也意味着你需要迭代这个数组两次。而我们的reduce方法只需要迭代一次数组就可以实现同样的效果。
eg:把数组中的值除以2,并且返回小于10的值:

const Array = [10,18,20,25];
const result = Array.reduce((finalList,arr) => {
    arr = arr / 2;
    if (arr < 10){
        finalList.push(arr);
    }
    return finalList;
},[]);
result;//[5,9]

2)使用reduce检测括号是否对齐封闭

话不多说,用例子解释
思路是定义一个名为 counter 的变量,它的初始值为 0 ,然后迭代字符串,迭代过程中碰到(就加 1,碰到)就减 1,如果括号前后对应的话,最终couter的值会是 0。

const isParensBalanced = (str) => {
  return str.split('').reduce((counter, char) => {
    if(counter < 0) { //matched ")" before "("
      return counter;
    } else if(char === '(') {
      return ++counter;
    } else if(char === ')') {
      return --counter;
    }  else { //matched some other char
      return counter;
    }

  }, 0); //<-- starting value of the counter
}

isParensBalanced('(())') // 0 <-- balanced
isParensBalanced('(asdfds)') //0 <-- balanced
isParensBalanced('(()') // 1 <-- not balanced
isParensBalanced(')(') // -1 <-- not balanced

3)使用 reduce 计算数组中的重复项

如果你想计算数组中的每个值有多少重复值,reducer 也可以快速帮到你。下面的例子我们计算数组中每个值的重复数量,并输出一个对象来展示:

var cars = ['BMW','Benz', 'Benz', 'Tesla', 'BMW', 'Toyota'];
var carsObj = cars.reduce(function (obj, name) { 
   obj[name] = obj[name] ? ++obj[name] : 1;
  return obj;
}, {});

carsObj; // => { BMW: 2, Benz: 2, Tesla: 1, Toyota: 1 }

2、使用Set数组去重

因为 Set 中的值不可重复,使用 Set 可以快速给数组去重。

let arr = [1, 1, 2, 2, 3, 3];
let deduped = [...new Set(arr)] // [1, 2, 3]

3、 数组解构

1)变换变量的值

let num1 = 1;
let num2 = 2;
[num1, num2] = [num2, num1];
console.log(num1) // 2
console.log(num2) // 1

2) 从函数接受和分配多个值

很多时候你的函数都会将多个数据放在数组内,以返回一个单一值(例如 Promise 函数,它的决议值只能是个单一值),我们可以使用数组解构简便的从返回结果中获取这些值。
下面的这个例子中,我们使用 fetch 发送了两个请求,并使用 Promise.all() 将两个结果保存在数组中,函数的执行结果是返回这个数组。

function getFullPost(){
  return Promise.all([
    fetch('/post'),
    fetch('/comments')
  ]);
}
const [post, comments] = await getFullPost();
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值