Reputation: 32893
I am inserting some data into an array but I am getting
,9,My firstname,My lastname,[email protected],123456789
out in my console. How can I remove comma from first element i.e. 9? here is my code
var data = new Array();
$(row_el.children("td")).each(function(i) {
var td = $(this);
//var data = td.html();
var td_el = td.attr('class');
//arr[i] = data;
if(!td.hasClass("element")) {
data[i] = td.html();
console.log(i + ": " + data);
}
});
I want output like this
9,My firstname,My lastname,[email protected],123456789
then I will pass this array to a function and loop through this array.
Upvotes: 0
Views: 1477
Reputation: 74076
Just use push()
(MDN docu) instead of setting to a specific position inside your array:
var data = new Array();
$(row_el.children("td")).each(function(i) {
var td = $(this);
//var data = td.html();
var td_el = td.attr('class');
//arr[i] = data;
if(!td.hasClass("element")) {
data.push( td.html() );
console.log(i + ": " + data);
}
});
The problem is, that not all the elements in the array processed by each()
result in an entry in your array. However, the index submitted to your callback (i
) counts upwards nonetheless. So if there are some elements, that do not result in an entry to your array, these positions are filled with undefined
(as long as you enter an element at a later position). These undefined
entries now result in an empty string when outputting it the way you do, thus resulting to your leading comma.
Upvotes: 3