Reputation: 819
I found this example that says:
var arr=$.map([0,1,2],function(n){
return [n,n+1];
});
Will make arr
a 6 item array. However, I don't understand why it isn't [[x,y],[x,y],[x,y]]
I need to know step by step what just happened. This map
functions seems very useful, I would hate to don't use it simply because I don't understand its behavior.
Upvotes: 2
Views: 247
Reputation:
You can double wrap the returned Array to avoid the flattened output.
var arr=$.map([0,1,2],function(n){
// v--------------v----- flattened
return [ [ n, n + 1 ] ];
// ^----------^------- inserted
});
arr; // [[0,1],[1,2],[2,3]]
IMO, you'll be better off using a standard .map()
function instead of jQuery's non-standard one.
var arr=[0,1,2].map(function(n){
return [ n, n + 1 ];
});
For unsupported browsers, you can use the compatibility patch from MDN.
Upvotes: 2
Reputation: 15350
$.map( [0,1,2], function(n){
return n + 4;
});
result: [4, 5, 6]
$.map( [0,1,2], function(n){
return [ n, n + 1 ];
});
result : [0, 1, 1, 2, 2, 3]
You can check the diference in the return
Upvotes: 0
Reputation: 185933
$.map
flattens the returned array:
A returned array will be flattened into the resulting array.
Source: http://api.jquery.com/jQuery.map/
Upvotes: 4