[英]javascript/jQuery Array concatenation?
我有一些简单的jQuery代码:
var response = Array()
$('.task-list').each(function() {
response.concat(response,$('#' + this.id).sortable('toArray'));
}
);
console.log(response);
我遇到的问题是我认为我使用concat不正确 - 结果是一个空数组。 当我使用数组推送时,它可以正常工作。
您必须设置response
新形成的数组的response
,如规范中所述。 您目前根本不使用返回值。
规范说对于.concat
,数组不会被更改,但会返回新数组:
当使用零个或多个参数item1,item2等调用concat方法时,它返回一个数组 ,该数组包含对象的数组元素,后跟每个参数的数组元素。
与.push
比较,它表示当前数组被更改,而是返回其他内容(新长度):
参数按照它们出现的顺序附加到数组的末尾。 作为调用的结果, 返回数组的新长度 。
所以:
response = response.concat($('#' + this.id).sortable('toArray'));
Concat返回连接数组,你想要这个
response = response.concat($('#' + this.id).sortable('toArray'));
简单的例子
var a = [1,2];
var b = [3,4];
a = a.concat( b ); // result is [1,2,3,4] which is correct
如果您执行以下操作
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.