作者:遇见你_天意_384 | 来源:互联网 | 2023-05-24 15:43
我有与此类似的代码,我试图用它来生成一个由三个子数组组成的数组:
f = [1, 2.5, 3, 10]
p = [1.2, 5.1, 6.3, 11]
r = [1, 1, 1, 1]
coords = _.reduce([f, p, r], function(memo, series){
if(series.length){
memo.push(_.map(series, function(s, i){
return {x: s, y: i*100};
}));
}
}, []);
console.log(coords);
最终结果应如下所示:
[
[{x:1,y:100},{x:2,y:2.5}...],
[{x:1,y:12},{x:2,y:51}...]
]
但是,当我尝试执行代码时,它会返回cannot read property push of undefined
.当我检查Chrome中的错误时,它指向我的memo.push
行.代码对我来说似乎没问题,但我无法弄清楚我的错误在哪里.任何帮助表示赞赏.
1> Bergi..:
你必须return
从你的reduce回调中获得一些东西才能成为新的累加器值.否则memo
将undefined
在下一次迭代和最终结果中返回...
A return memo;
会修复此问题,但我觉得你实际上不想使用reduce
:
var coords = _.map(_.filter([f, p, r], function(series) {
return series.length; // > 0
}), function(nonemptyseries) {
return _.map(nonemptyseries, function(s, i){
return {x: s, y: i*100};
});
});