how to form an array of arrays in jQuery
How to make an array of arrays like
{ [1,2,3],[2,3,4],[2,34,55] }
in jQuery ?
$(document).ready(function() {
var row = 4;
var开发者_JS百科 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());
});
iIn the above code I'm trying to create a array Total()
with the elements as arrays (item()
), but how ever the Total()
array has only one object that too the last item()
array.
The problem is that you're reusing the same items
array on each loop. Instead, create a new items
array:
$(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());
});
When you set the length
property of an array to 0
, you're removing all of its array elements but it's still the same array, so you ended up pushing the same array onto your totals
array repeatedly.
Move the creation of the items array into the outer loop so that you create a new array for each iteration. Otherwise you will be adding the same array to total
over and over, so you will end up with an array full of references to the same array, which contains only the values from the last iteration.
Don't use the undefined
"constant", as it's not a constant. Check the type of the property instead.
$(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());
});
First of all, an array of arrays literal should have two sets of []
, not mixed []
and {}
: [ [1,2,3],[2,3,4],[2,34,55] ]
Also, instead of
items.length = 0;
do this:
var items = [];
What you're doing now is kind of like trying to expand your friend's circle of acquaintances by taking another person and introducing him to her repeatedly, only changing his clothes, wig and fake moustache every time. Despite the different looks, your friend will only get one new acquaintance.
精彩评论