Return JavaScript 中的三元运算符减少

Return ternary operator in JavaScript reduce

我有这样的数据结构:

var example = [
    { name: "item1", year: 2013, value: 100 },
    { name: "item1", year: 2012, value:  97 },
    { name: "item3", year: 2013, value:  93 },
    { name: "item3", year: 2012, value:  91 },
    { name: "item2", year: 2012, value:  -6 },
    { name: "item2", year: 2011, value:  -5 },
    { name: "item4", year: 2012, value: -36 },
    { name: "item3", year: 2011, value:  93 },
    { name: "item4", year: 2013, value: -35 },
    { name: "item1", year: 2011, value:  98 },
    { name: "item2", year: 2013, value:  -7 },
    { name: "item4", year: 2011, value: -37 },
    { name: "item5", year: 2013, value:  58 },
    { name: "item5", year: 2012, value:  55 },
    { name: "item5", year: 2011, value:  54 }
];

我正在使用此函数获取单个元素的数组:

example.reduce(function (prev, curr) {
    if (prev.indexOf(curr.name) === -1) prev.push(curr.name);
    return prev;
}, []);

虽然这可行,但我尝试使用三元运算符来提高可读性,如下所示:

example.reduce(function (prev, curr) {
    return prev.indexOf(curr.name) === -1 ? prev.push(curr.name) : prev;
}, []);

我在 Chrome 中收到以下错误:

Uncaught TypeError: prev.indexOf is not a function
    at <anonymous>:3:13
    at Array.reduce (native)
    at <anonymous>:2:9
    at Object.InjectedScript._evaluateOn (<anonymous>:895:140)
    at Object.InjectedScript._evaluateAndWrap (<anonymous>:828:34)
    at Object.InjectedScript.evaluate (<anonymous>:694:21)

这是为什么?

这是因为调用 .push() 会 return 数组的新长度是一个数字,所以第二次调用 prev 将是一个数字 (1) 而不是'没有推送方法。

Returns

The new length property of the object upon which the method was called.

所以使用 if 条件会更好。

如果您仍想使用三元运算符,可以使用像

这样的 hacky 解决方案
var b = example.reduce(function (prev, curr) {
    return prev.indexOf(curr['name']) === -1 ? prev.push(curr['name']) && prev : prev;
}, []);

将您的三元运算符替换为 &&, 而不是 ?:,如下所示:

example.reduce(function (prev, curr) {
    return prev.indexOf(curr.name) < 0 && prev.push(curr.name), prev;
}, []);

在这种情况下,我们不使用三元运算符,而是使用逻辑 AND 来测试是否 prev.indexOf(curr.name) < 0,如果是,则执行 prev.push(curr.name)。但是,我们总是returnprev因为comma operator.

正如我在评论中提到的,您的代码无法正常工作,因为 .push doesn't return the original array. It returns the new length of the array. You could replace .push with .concat 但它的效率非常低。我上面介绍的方法比较好