Reputation: 2708
I want to create dynamic array of taxes in javascript for which I used the following code:
$("table").on("focusout",".tax_amount",function(e){
var IDs = new Array();
$('.tax_amount').each(function(){
k = this.id;
if(typeof IDs[k] === 'undefined') {
IDs[k] = parseFloat(this.value);
}else{
IDs[k]+= parseFloat(this.value);
}
});
console.log(IDs);
});
Now I want to iterate that IDs array to create the table. But .length & .size() are not working on IDs array. When I see the result of array in console it shows following
Unable to get how to use that array for $.each.
I have solved it using following code:
var IDs = {}
$('.tax_amount').each(function(){
k = this.id;
if(k in IDs) {
IDs[k]+= parseFloat(this.value);
}else{
IDs[k] = parseFloat(this.value);
}
});
console.log(IDs.length);
$.each(IDs,function(key,index){
console.log(key);
console.log(index);
});
Thanks a lot Quentin for guiding in the right direction.
Upvotes: 2
Views: 535
Reputation: 87
I hope that your requirement is this
$("table").on("focusout",".tax_amount",function(e){
var IDs = new Array();
$('.tax_amount').each(function(){
k = this.id;
if(typeof k === 'undefined') {
IDs.push(parseFloat(this.value));
}else{
k += parseFloat(this.value);
IDs.push(k);
}
});
console.log(IDs);
});
Upvotes: 0
Reputation: 681
Use var arr = new Array();
then arr.push(itemValue);
to enter elements as many as you wish
for iterating through array and access values,
arr.forEach(myFunction);
function myFunction(item, index) {
console.log(item);
console.log(index);
}
Upvotes: 0
Reputation: 943210
size()
doesn't work because Array objects don't have a size method.
length
doesn't work because:
The length property represents an unsigned, 32-bit integer that is always numerically greater than the highest index in the array.
You haven't put any indexes in the array.
You've added named properties.
$.each
doesn't work because, when given an array, it iterates over the indexes, and again you haven't given it any.
If you want to use named properties, use an object, not an array. Arrays are designed for numerically indexed and ordered data.
Upvotes: 8