javascript - jQuery equivalent to Prototype collect and map functions? - Stack Overflow

Does jQuery offer an equivalent iterator function to "collect" and "map" in Prototy

Does jQuery offer an equivalent iterator function to "collect" and "map" in Prototype? These functions return the result of applying an iterator to each element:

Thanks!

Does jQuery offer an equivalent iterator function to "collect" and "map" in Prototype? These functions return the result of applying an iterator to each element: http://www.prototypejs/api/enumerable/collect

Thanks!

Share Improve this question edited Dec 28, 2011 at 22:29 Rob W 349k87 gold badges807 silver badges682 bronze badges asked Apr 27, 2011 at 19:30 CrashalotCrashalot 34.6k63 gold badges284 silver badges460 bronze badges 0
Add a ment  | 

2 Answers 2

Reset to default 5

There's a "map()" but no "reduce()" or "collect()". The jQuery people have a considerable history of being resistant to adding a "reduce()" in the absence of clear benefit to the jQuery core code itself.

You can pick up and extend simple implementations of functions like that from the Functional.js library.

Also, be warned that the jQuery "map" facility has a couple of questionable features that are handy at times but a serious pain at others. Specifically, the callback function passed in to "map()" returns a value for the result array, as you might expect. However there are two special cases:

  1. If the function returns null or undefined, then nothing is added to the result array; in other words, it's interpreted as a request to skip that element. This makes it hard to have a result array with explicitly null entries.
  2. If the function returns an array, then the array is interpolated into the resulting array. In other words, if the function returns an array of 10 items, then the result array (that is, the array to be returned eventually from the call to "map()") will be augmented by 10 new elements, instead of by one element whose value is the array of 10 things.

Both those treats are handy sometimes but after spending half a day discovering the second one (yes, it's documented) I've got some painful memories :-)

The jQuery equivalent is .map() (see docs)

So if in Prototype you have:

['Hitch', "Hiker's", 'Guide', 'To', 'The', 'Galaxy'].collect(function(s) {
  return s.charAt(0).toUpperCase();
}).join(''); // -> 'HHGTTG'

Simply replace collect with map (or if already using map you don't need to change anything!):

['Hitch', "Hiker's", 'Guide', 'To', 'The', 'Galaxy'].map(function(s) {
  return s.charAt(0).toUpperCase();
}).join(''); // -> 'HHGTTG'

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744928105a4601566.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信