简体   繁体   中英

javascript/jQuery Array concatenation?

I have some simple jQuery code:

var response = Array()
$('.task-list').each(function() {
  response.concat(response,$('#' + this.id).sortable('toArray'));
}
);
console.log(response);

The problem I'm having is that I think I'm using concat improperly- the result is an empty array. When I use array push, it works correctly.

You have to set response to the newly formed array, as described in the specification. You currently don't use the return value at all.

The specification says that for .concat , the array is not altered, but the new array is returned:

When the concat method is called with zero or more arguments item1, item2, etc., it returns an array containing the array elements of the object followed by the array elements of each argument in order.

Compare with .push , which says the current array is altered, and that something else is returned instead (the new length):

The arguments are appended to the end of the array , in the order in which they appear. The new length of the array is returned as the result of the call.

So:

response = response.concat($('#' + this.id).sortable('toArray'));

Concat returns the concatenated array, you want this instead

response = response.concat($('#' + this.id).sortable('toArray'));

Simple example

var a = [1,2]; 
var b = [3,4]; 

a = a.concat( b ); // result is [1,2,3,4] which is correct 

If you do the following

a = a.concat( a , b ); // result is [1, 2, 1, 2, 3, 4] not what you want. 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM