数组forEach()vs reduce() [英] Array forEach() vs reduce()

查看:220
本文介绍了数组forEach()vs reduce()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您认为什么是最好的方法?

what do you think is the best way to do ?

减少方式:

const result = Object.keys(params).reduce(
      (previous, key) => {
        if (this.model.hasOwnProperty(key)) previous[key] = this.model[key](params[key]);
        return previous;
  }, {});

每种方式:

const result = {};
Object.keys(params).forEach(key => {
      if (this.model.hasOwnProperty(key)) result[key] = this.model[key](params[key]);
    });

我正在使用airbnb eslint,并且由于我修改了previous(无参数重新分配),它不喜欢减少方式

I'm using airbnb eslint and it doesn't like the reduce way since I modify previous (no-param-reassign)

推荐答案

我认为reduce更好,因为它不会在整个地方溢出var.您可以使它变得更好一点,imo.

I think the reduce is a lot nicer because it doesn't spill vars all over the place. You could make it a little better yet, imo.

var result = Object.keys(params).reduce((res,k)=>
  this.model.hasOwnProperty(k)
    ? Object.assign(res, {[k]: this.model[k](params[k])})
    : res, {});

这篇关于数组forEach()vs reduce()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆