I have code which looks similar to this, which I'm trying to use to produce an array consisting of three sub-arrays:
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);
The end result should look like:
[
[{x:1,y:100},{x:2,y:2.5}...],
[{x:1,y:12},{x:2,y:51}...]
]
However, when I attempt to execute the code, it returns cannot read property push of undefined
. When I inspect the error in Chrome, it points me to the memo.push
line. The code seems ok to me, but I can't figure out where my error is. Any help is appreciated.
I have code which looks similar to this, which I'm trying to use to produce an array consisting of three sub-arrays:
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);
The end result should look like:
[
[{x:1,y:100},{x:2,y:2.5}...],
[{x:1,y:12},{x:2,y:51}...]
]
However, when I attempt to execute the code, it returns cannot read property push of undefined
. When I inspect the error in Chrome, it points me to the memo.push
line. The code seems ok to me, but I can't figure out where my error is. Any help is appreciated.
2 Answers
Reset to default 9You must return
something from your reduce callback to bee the new accumulator value. Otherwise memo
will e back as undefined
in the next iteration and end result…
A return memo;
would fix this, however I feel that you actually don't want to use 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};
});
});
The _.reduce
method needs to return some value, for the next iteration to take as input.
If you step through the code (put a debugger
statement before the _.reduce
), you can see that it succeeds the first time, but memo
is undefined on the second loop.
In this case, you likely want to return memo
from the reduce, whether you've added new elements to it or not (if the series was empty, keep going to the next series).
Something like:
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
};
}));
}
return memo;
}, []);
console.log(coords);
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742399995a4436718.html
评论列表(0条)