concatenate Array Recursively
I want to merge recursi开发者_开发百科vely arrays..
My code is:
var allitemorder;
var itemorder;
$('.divclass').each(function () {
itemorder = $(this).sortable('toArray');
allitemorder = $.merge([], itemorder);
});
Kindly help.
You need just a slight change, like this:
var allitemorder = [], itemorder;
$('.divclass').each(function () {
itemorder = $(this).sortable('toArray');
$.merge(allitemorder, itemorder);
});
Or the shorter:
var allitemorder = [];
$('.divclass').each(function () {
$.merge(allitemorder, $(this).sortable('toArray'));
});
$.merge(first, second)
takes the elements from the second array and puts them in the first, so you need to pass the array you want to accumulate into as the first argument each time.
Try this:
var array = $('.divclass').map(function () {
return $(this).sortable('toArray');
}).get();
Returning an array in .map()
automatically merges the array into the jQuery object created. Then .get()
retrieves the final array.
allitemorder = $.merge([], itemorder);
Looks like you are resetting allitemorder with itemorder. So shouldn't this be :
allitemorder = $.merge(allitemorder, itemorder);
EDIT:
as Nick states: $.merge(allitemorder, itemorder);
suffices (without setting the variable allitemorder again). I would totally go with his shorthand solution.
精彩评论