New to javascript arrays, need some help
I have an assignment in which I need to make two arrays (NAME and SALES). I need to populate the array of up to 100 components. Then, I need to calculate gross pay using a calcPay() function. I am having 开发者_开发知识库trouble figuring out how to get the function to work, it either prints the resulting table with the Pay column as 'undeclared', or it just stops working when it comes to that spot, no matter how many NAMES and SALES are entered into the array. I have this in the body script:
var i=0;
var NAME = new Array();
var SALES = new Array();
do
{
NAME[i]=getName();
SALES[i]=getSales();
i++;
var again=confirm("Would you like to enter another salesperson's stats?");
}while(again && i<=100);
var i=0;
for (var i=0;i<NAME.length;i++)
{
printRow();
}
And this is the header:
function getName()
{
do
{
var name=prompt("What is the salesperson's full name?");
}while (name==""||name==null);
return name;
}
function getSales()
{
do
{
var sales=prompt("Please enter salesperson's sales.");
}while(sales==""||isNaN(sales));
return parseFloat(sales);
}
calcPay(sales)
{
var pay=sales*.1+1000;
return pay;
}
function printRow()
{
document.write("<tr>");
document.write("<td>"+NAME[i]+"</td>");
document.write("<td>"+SALES[i]+"</td>");
var payment=calcPay(SALES[i]);
document.write("<td>"+payment+"</td>");
document.write("</tr>");
}
This is not the full extent of the assignment by any means, I just want to make sure that I have a handle on the feeding and manipulating of the arrays (which I don't, obviously). Thanks for any tips.
Generally - your code works, find it here:
http://jsfiddle.net/osher/GhZSf/
However - there is a missing "function" before calcPay
calcPay(sales)
{
var pay=sales*.1+1000;
return pay;
}
should be
function calcPay(sales)
{
var pay=sales*.1+1000;
return pay;
}
that's all
name and sales are out of scope this function will not do what you think it will and even if it does it is wrong.
Use an if statement .
function getName()
{
do
{
var name=prompt("What is the salesperson's full name?");
}while (name==""||name==null);
return name;
}
function getSales()
{
do
{
var sales=prompt("Please enter salesperson's sales.");
}while(sales==""||isNaN(sales));
return parseFloat(sales);
}
精彩评论