[英]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.