2011-04-28 20 views
3

陣列如何使數組的數組等 {[1,2,3],[2,3,4],[2,34,55]}如何形成陣列中的Jquery

在jQuery中?

$(document).ready(function() { 
    var row = 4; 
    var items = []; 
    var total = []; 
    $('#test tr:eq(' + row + ') td').each(function(colindex, col) { 
     //alert(colindex); 
     t = $(this).contents(); 
     items.length = 0; 
     $.each(t, function(i, val) { 
      if (val.tagName != 'BR') { 
       if (val.innerHTML == undefined) { 
        items.push(val.data); 
       } 
       else 
        items.push(val.innerHTML); 
      } 
      //alert(items.toString()); 
     }); 
     total.push(items); 
    }); 
    alert(total.toString()); 
}); 
在上面的代碼

我試圖創建一個元素數組一個陣列共()(項目()) 但怎麼過總()數組只有一個對象,也將最後一個項目()數組。

可以一個請建議我SOLN

+3

{[1,2,3],[2,3,4],[2,34,55]} =>包含數組的對象。 [[1,2,3],[2,3,4],[2,34,55]] =>包含數組的數組 – stecb 2011-04-28 07:20:08

+0

@stecb:'{[1,2,3],[2,3,4 ],[2,34,55]}'是一個無效的對象字面值,不是包含數組的對象(它沒有任何屬性名稱)。但是,是的,當作爲文字書寫時,數組數組的正確表示法確實是'[[1,2,3],[2,3,4],[2,34,55]]'。 – 2011-04-28 07:24:35

+0

你是絕對正確的T.J. :) ..ty! – stecb 2011-04-28 08:05:38

回答

3

的問題是,你打算重用在每次循環相同items陣列。相反,創建一個新的items陣列:

$(document).ready(function() { 
    var row = 4; 
    var items;  // <============= Don't need to initialize here 
    var total = []; 
    $('#test tr:eq(' + row + ') td').each(function(colindex, col) { 
     //alert(colindex); 
     t = $(this).contents(); 
     items = []; // <============== Create each new `items` array here 
     $.each(t, function(i, val) { 
      if (val.tagName != 'BR') { 
       if (val.innerHTML == undefined) { 
        items.push(val.data); 
       } 
       else 
        items.push(val.innerHTML); 
      } 
      //alert(items.toString()); 
     }); 
     total.push(items); 
    }); 
    alert(total.toString()); 
}); 

當數組的length屬性設置爲0,你移除所有的數組元素,但它仍然是相同的陣列,所以你最終推相同將數組重複到您的totals陣列上。

+0

感謝每一個人的快速反應..! – deathcaller 2011-04-28 07:34:14

+0

@deathcaller:不用擔心,很高興幫助。 – 2011-04-28 09:20:42

+0

@deathcaller:只要將其標記出來,請參閱@ guffa關於'if(val.innerHTML == undefined)'檢查的註釋。真的最好做'if(typeof val.innerHTML ==='undefined')'(注意'==='而不是'==',儘管在這種情況下,它並不重要)。 – 2011-04-28 09:27:29

0

首先,數組字面應該有兩套[]的陣列,而不是混合[]{}[ [1,2,3],[2,3,4],[2,34,55] ]

此外,取代

items.length = 0; 

做到這一點:

var items = []; 

你現在在做什麼有點像試圖擴大你的朋友的熟人圈子另一個人反覆介紹他,只是每次換衣服,假髮和假鬍鬚。儘管外表不同,你的朋友只會得到一個新朋友。

1

將items數組的創建移動到外部循環中,以便爲每次迭代創建一個新數組。否則,你會一次又一次地向total添加相同的數組,所以你最終會得到一個數組,其中包含了對同一個數組的引用,它只包含最後一次迭代的值。

請勿使用undefined「常量」,因爲它不是常量。改爲檢查屬性的類型。

$(document).ready(function() { 
    var row = 4; 
    var total = []; 
    $('#test tr:eq(' + row + ') td').each(function(colindex, col) { 
    t = $(this).contents(); 
    // create a new array for each iteration: 
    var items = []; 
    $.each(t, function(i, val) { 
     if (val.tagName != 'BR') { 
     if (typeof val.innerHTML == 'undefined') { 
      items.push(val.data); 
     } else { 
      items.push(val.innerHTML); 
     } 
     } 
    }); 
    total.push(items); 
    }); 
    alert(total.toString()); 
});