简体   繁体   中英

Using underscore.js can reduce return an array?

I'm trying to use reduce to return an array like so:

var myArray = [1,2,3];
_.reduce(myArray, function (seed, item) { return seed.push(item);}, []);

I expect that it will produce an array just like myArray. Instead for the first item, seed is an array. Then for the second item, seed is a number. That causes an error and the third item is never reached.

Whats happening here?

Actually, seed.push() does not return the modified seed . Do the following, and it's right:

_.reduce(myArray, function (seed, item) { seed.push(item); return seed; }, []);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM