最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - $(...)..map(...).reduce is not a function - Stack Overflow

programmeradmin2浏览0评论

I'm trying to calculate the sum of the height of a couple elements in the page using map & reduce. For unknown reasons this is throwing me the following exception:

VM52933:2 Uncaught TypeError: $(...).map(...).reduce is not a function(…)

$('.items')
    .map( (index,slide) => $(slide).height() )
    .reduce( (prev, next) => prev + next, 0 )

.map returns a valid array:

[48, 48, 48, 75, 48]

If i do the map separately ( [48, 48, 48, 75, 48].reduce(...) ) it works. What am I doing wrong here?

I'm trying to calculate the sum of the height of a couple elements in the page using map & reduce. For unknown reasons this is throwing me the following exception:

VM52933:2 Uncaught TypeError: $(...).map(...).reduce is not a function(…)

$('.items')
    .map( (index,slide) => $(slide).height() )
    .reduce( (prev, next) => prev + next, 0 )

.map returns a valid array:

[48, 48, 48, 75, 48]

If i do the map separately ( [48, 48, 48, 75, 48].reduce(...) ) it works. What am I doing wrong here?

Share Improve this question edited Jul 26, 2016 at 19:58 André Senra asked Jul 26, 2016 at 19:55 André SenraAndré Senra 2,2252 gold badges12 silver badges13 bronze badges 5
  • 12 Add .get() between the map and reduce. Otherwise you have a jQuery object containing an array. – Niet the Dark Absol Commented Jul 26, 2016 at 19:57
  • can you post a small example with .items here in the fiddle? – webdeb Commented Jul 26, 2016 at 19:57
  • That's because .map method returns jQuery object, not array. – hindmost Commented Jul 26, 2016 at 19:58
  • jQuery-objects are lists, but they ain't Arrays. And reduce is a method of Array – Thomas Commented Jul 26, 2016 at 19:58
  • @NiettheDarkAbsol please add your comment as an answer so I can mark it as solution. It worked. Thank you. – André Senra Commented Jul 26, 2016 at 20:01
Add a comment  | 

2 Answers 2

Reset to default 13

It is because you are when you do $('.items') its an array like structure but not array. If you see the prototype it dof NodeList type ad it doesn't have reduce method on it. If you pass this from Array.from then it will convert it to proper array and you will be able to apply reduce, map and all the other array functions.

More details can be found at

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from

do something like

Array.from($('.items'))
.map( (slide) => $(slide).height() )
.reduce( (prev, next) => prev + next, 0 );

Try this:

$('.items')
    .toArray()
    .map( (index,slide) => $(slide).height() )
    .reduce( (prev, next) => prev + next, 0 );

Thanks to @thomas for pointing this out.

发布评论

评论列表(0)

  1. 暂无评论