2011-09-21 23 views
1

我有一些簡單的jQuery代碼:javascript/jQuery數組串聯?

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

我遇到的問題是,我想我使用CONCAT improperly-的結果是一個空數組。當我使用數組推送時,它可以正常工作。

+0

什麼是你想完成的任務。你想要添加元素到jQuery對象嗎? –

回答

4

你必須設置response到新形成陣列,如說明書中所述。您目前根本不使用返回值。

的規範指出,爲.concat,該陣列沒有改變,但返回新的數組:

當concat方法被調用,零個或多個參數項目1,項目2,等等,它返回一個數組,其中包含對象的數組元素,然後按順序包含每個參數的數組元素。

.push比較,其中說,目前的陣列改變,而別的東西返回,而不是(新長度):

的參數是附加結束數組,按它們出現的順序排列。作爲調用的結果,該陣列的新長度返回

所以:

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

的毗連返回級聯陣列,你要想這不是

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.