开发者

jQuery equivalent to Prototype collect and map functions?

开发者 https://www.devze.com 2023-02-28 22:59 出处:网络
Does jQuery offer an equivalent iterator function to \"collect\" and \"map\" in Prototype? These functions return the result of applying an iterator to each开发者_C百科 element: http://www.prototypejs

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

Thanks!


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'
0

精彩评论

暂无评论...
验证码 换一张
取 消