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.

Share Improve this question asked Jan 28, 2015 at 19:47 Kevin WhitakerKevin Whitaker 13.4k13 gold badges54 silver badges94 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 9

You 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);

本文标签: