1

虽然这纯粹是一个练习,但鉴于此代码:

var someCondition = (....);
var res = [];
if (someCondition) {
   res.push("A");
}
res.push("B");
if (someCondition) {
   res.push("C")
}
return res;

表达列表的更“实用”的方式是什么?

我可能会是这样的(在 JS 中,使用 underscorejs 减少,基本上是折叠)

_.reduce(["A", "B", "C"], function (memo, value, index) {
     if (index === 0 || index === 2) {
        if (someCondition) {
           memo.push(value);
        }
     } else {
        memo.push(value);
     }
}, []);

或使用过滤器:

_.filter(["A", "B", "C"], function (value, index) {
    if (index === 0 || index === 2) {
       return someCondition;
    } else {
       return true;
    }
});

现在,这听起来有点难看......我在这里错过了一个明显的解决方案吗?

4

3 回答 3

0

How about filter?

_.filter(['A', 'B', 'C'], function(value, index){
    if (index === 1 || index === 2) {
        return someCondition;
    }
    return true;
});
于 2013-10-18T09:40:22.930 回答
0

就个人而言,我不会将其视为过滤函数的候选者,因为数组索引很重要。对我来说,第一种功能方法是这样的:

[].concat(someCondition ? ['A'] : [],
          ['B'],
          someCondition ? ['C'] : []);

这里的优点是与特定索引的分离以及更容易插入其他项目的能力。

于 2013-10-20T12:00:16.290 回答
0

表达你想做的事情的方式是用filter.

假设你有一个条件:

function isEven(n) {
  return n % 2 === 0;
}

以及从0到的数字列表20,包括:

const A = [...Array(21).keys()];

如果您想要该列表中的偶数,您可以执行以下操作:

A.filter((n) => isEven(n));

同样,如果你想要奇怪的:

A.filter((n) => isOdd(n));

重要的事情,也许是函数式编程最重要的思想,是数组没有被那个过程修改A:函数只是简单地接受和返回数据,每次发送的数据是函数调用的结果都是一样的相同。没有状态管理,也没有副作用。

于 2016-12-29T17:51:58.747 回答