我有一个这样的数据结构:
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
函数不会返回相同的数组。 - Mritunjay.push
不会返回一个数组,而是返回新数组的长度。 - Aadit M Shah