I seem to be getting a NaN error as the result in my JavaScript code.
I'm pretty new to this, would appreciate any help.
Solved by giving value to the total var.
I seem to be getting a NaN error as the result in my JavaScript code.
I'm pretty new to this, would appreciate any help.
Solved by giving value to the total var.
There are a couple of problems:
parseFloat
instead of using strings.total
(this is what causes the nan
)function tax() {
var price = new Array(10);
var quant = new Array(10);
var taxam = 18;
var total = 0;
for(i=0;i<10;i++) {
quant[i] = parseFloat(prompt("Insert Quantity: "));
price[i] = parseFloat(prompt("Insert Price: "));
}
for(i=0;i<10;i++) {
total += price[i] * quant[i];
}
total = total * (taxam / 100);
alert(total);
}
I guess with this var price = [10]
you were trying to create an array with 10 numbers, but that is not the way it works in Javascript var price = [10]
will give you an array with 10 at the 0th position. The only other tweak I would make there is make var price = [1,2,3,4,5,6,7,8,9,10]
to actually achieve what you set out for initally
First of all, JavaScript is not Java ;)
You seem to try to initialize your arrays with a length of 10. This works in Java but in Javascript an array is dynamic and writing :
myArray = [10];
will just set the value 10
in the first index of the array.
Then, as you prompt the user to input numbers, the numbers will be interpreted as a string. So it would be good to cast it to a number before working with it. To cast it :
var value = '10000';
valueAsInt = parseFloat('10000',10);
//or simply
valueAsInt = +value;
Now we come to your problem, as total
is not initialised, the first affectation will be
undefined += n;
this will give a NaN
.
So just initialise total
before using it :
var total = 0;
you have to initialize total variable first because it is undefined initially
var total = 0;
You have to parse the String variables to a Number:
function tax() {
var price = [10];
var quant = [10];
var taxam = 18;
var total = 0;
for(i=0;i<10;i++) {
quant[i] = Number(prompt("Insert Quantity: "));
price[i] = Number(prompt("Insert Price: "));
}
for(i=0;i<10;i++) {
total += price[i] * quant[i];
}
total = total * (taxam / 100);
alert(total);
}
tax()