虽然这纯粹是一个练习,但鉴于此代码:
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;
}
});
现在,这听起来有点难看......我在这里错过了一个明显的解决方案吗?