简体   繁体   English

javascript / jQuery数组连接?

[英]javascript/jQuery Array concatenation?

I have some simple jQuery code: 我有一些简单的jQuery代码:

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. 我遇到的问题是我认为我使用concat不正确 - 结果是一个空数组。 When I use array push, it works correctly. 当我使用数组推送时,它可以正常工作。

You have to set response to the newly formed array, as described in the specification. 您必须设置response新形成的数组的response ,如规范中所述。 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: 规范说对于.concat ,数组不会被更改,但会返回新数组:

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. 当使用零个或多个参数item1,item2等调用concat方法时,它返回一个数组 ,该数组包含对象的数组元素,后跟每个参数的数组元素。

Compare with .push , which says the current array is altered, and that something else is returned instead (the new length): .push比较,它表示当前数组更改,而是返回其他内容(新长度):

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 Concat返回连接数组,你想要这个

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. 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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