javascript/jQuery数组连接?
我有一些简单的jQuery代码:javascript/jQuery数组连接?,javascript,jquery,Javascript,Jquery,我有一些简单的jQuery代码: var response = Array() $('.task-list').each(function() { response.concat(response,$('#' + this.id).sortable('toArray')); } ); console.log(response); 我遇到的问题是,我认为我使用concat不正确-结果是一个空数组。当我使用数组推送时,它可以正常工作。Concat返回连接的数组,您希望使用它吗 response
var response = Array()
$('.task-list').each(function() {
response.concat(response,$('#' + this.id).sortable('toArray'));
}
);
console.log(response);
我遇到的问题是,我认为我使用concat不正确-结果是一个空数组。当我使用数组推送时,它可以正常工作。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.
您必须将
response
设置为新形成的数组,如规范中所述。您当前根本不使用返回值
规范规定,对于.concat
,数组不会更改,但会返回新数组:
当使用零个或多个参数item1、item2等调用concat方法时,它返回一个数组,该数组包含对象的数组元素,后跟每个参数的数组元素
与.push
相比,push表示当前数组已更改,并返回其他内容(新长度):
参数按其出现的顺序被添加到数组的末尾。作为调用的结果,返回数组的新长度
因此:
你想完成什么。您正在尝试向jQuery对象添加元素吗?
response = response.concat($('#' + this.id).sortable('toArray'));