admin管理员组文章数量:1336194
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);
本文标签:
版权声明:本文标题:javascript - Underscore JS: reducing into an array causes undefined method error on the accumulator - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742399994a2467693.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论