Reduce resource usage of this JS program? - javascript

I wrote the following JS program, which i'm running from the command line using node.
//step one: create an array of remaining creatures
var remainingCreatures = [];
//some config variables:
var amt = 1000; //amount of creatues generated
var maxhlt = 1000; //max value for creature health stat
var minhlt = 100; //min value for creature health stat
var maxatk = 100; //max value for creature attack stat
var minatk = 1; //min value for creature attack stat
function remove(target) { //helper function to easily remove creatues from the array
var index = remainingCreatures.indexOf(target);
if (index > -1) {
remainingCreatures.splice(index, 1);
}
}
//generate creatures
//each creature has an Attack, Health, and Aggressiveness , as well as Instabillity, the average of the three
//A creature's Instabillity is added to the attack points of its opponent in fights.
for (var i = 0; i < amt; i++) {
var atkVal = Math.floor((Math.random() * maxatk) + minatk);
var hltVal = Math.floor((Math.random() * maxhlt) + minhlt);
var insVal = (atkVal + hltVal) / 2;
remainingCreatures[i] = {num: i, atk: atkVal, hlt: hltVal, ins: insVal, fts: 0, ihlt: hltVal};
}
console.log(amt + " creatues generated, starting melee...");
function fight(cr1, cr2) { //function to handle fighting, randomly creates creature pairs and has them fight
function attack(a, b) {
console.log("[ROUND 1] Creature 1 (#" + a.num + ") is attacking first.");
b.hlt = b.hlt - (a.atk + b.ins);
console.log("[HIT] Creature #" + b.num + " health reduced to " + b.hlt);
if (b.hlt <= 0) {
console.log("[DEATH] Creature #" + b.num + " Eliminated");
remove(b);
} else {
console.log("[ROUND 2] Creature 2 (#" + b.num + ") is attacking second.");
a.hlt = a.hlt - (b.atk + a.ins);
console.log("[HIT] Creature #" + a.num + " health reduced to " + a.hlt);
if (a.hlt <= 0) {
console.log("[DEATH] Creature #" + a.num + " Eliminated");
remove(a);
}
}
}
console.log("[FIGHT] Pair generated: Creature #" + cr1.num + " and Creature #" + cr2.num);
cr1.fts++;
cr2.fts++;
if (cr1.ins <= cr2.ins) {
attack(cr1, cr2);
} else {
attack(cr2, cr1);
}
}
for(;true;) {
if(remainingCreatures.length == 1) break;
fight(remainingCreatures[Math.floor(Math.random() * remainingCreatures.length)], remainingCreatures[Math.floor(Math.random() * remainingCreatures.length)]);
}
console.log(" ");
console.log("[WIN] Creature #" + remainingCreatures[0].num + " has won!");
console.log("Starting array size was " + amt + " creatures")
console.log(remainingCreatures[0]);
For some reason, this starts to slow down and eventually choke when amt is set to really big numbers, like one million. For reference, that's the number of objects that will be generated and added to an array - as you can probably see in the code, this array gets looped through a lot. But even with one million objects, each object is only around 80 bytes, maximum. And the calculations this program is doing are very basic.
So my question is: why is running this program so resource intensive, and how can I fix or mitigate it without changing the function of the program too drastically?

First of all, a million of anything will take a toll on performance, no matter how small.
The other issue is that your design is inherently inefficient.
Look at your remove() function. It first finds the index of the element, then removes it. If you have one million elements in that array, on average, it will need to compare the passed value with 500,000 elements just to find it before it can remove. There's one easy way to fix this; pass indices directly rather than using .indexOf.
function fight(ind1, ind2) { //function to handle fighting, randomly creates creature pairs and has them fight
var cr1 = remainingCreatures[ind1];
var cr2 = remainingCreatures[ind2];
function attack(a, b) {
console.log("[ROUND 1] Creature 1 (#" + a.num + ") is attacking first.");
b.hlt = b.hlt - (a.atk + b.ins);
console.log("[HIT] Creature #" + b.num + " health reduced to " + b.hlt);
if (b.hlt <= 0) {
console.log("[DEATH] Creature #" + b.num + " Eliminated");
remove(ind2);
} else {
console.log("[ROUND 2] Creature 2 (#" + b.num + ") is attacking second.");
a.hlt = a.hlt - (b.atk + a.ins);
console.log("[HIT] Creature #" + a.num + " health reduced to " + a.hlt);
if (a.hlt <= 0) {
console.log("[DEATH] Creature #" + a.num + " Eliminated");
remove(ind1);
}
}
}
console.log("[FIGHT] Pair generated: Creature #" + cr1.num + " and Creature #" + cr2.num);
cr1.fts++;
cr2.fts++;
if (cr1.ins <= cr2.ins) {
attack(cr1, cr2);
} else {
attack(cr2, cr1);
}
}
for(;true;) {
if(remainingCreatures.length == 1) break;
fight(Math.floor(Math.random() * remainingCreatures.length), Math.floor(Math.random() * remainingCreatures.length));
}
There aren't many other ways to easily improve performance, but that alone should be enough. To make your code more readable, though, consider replacing this:
for(;true;) {
if(remainingCreatures.length == 1) break;
fight(Math.floor(Math.random() * remainingCreatures.length), Math.floor(Math.random() * remainingCreatures.length));
}
with this:
// Consider using === and !== as best practice, but not necessary here
while (remainingCreatures.length != 1)
fight(Math.floor(Math.random() * remainingCreatures.length), Math.floor(Math.random() * remainingCreatures.length));
(See this link for info on that comment.)

Related

Better way to do this If statement?

Pretty simple: I wrothe the following if/else statement:
if (cr1.ins <= cr2.ins) {
console.log("[ROUND 1] Creature 1 (#" + cr1.num + ") is attacking first.");
cr2.hlt = cr2.hlt - (cr1.atk + cr2.ins);
console.log("[HIT] Creature #" + cr2.num + " health reduced to " + cr2.hlt);
if (cr2.hlt <= 0) {
console.log("[DEATH] Creature #" + cr2.num + " Eliminated");
remove(cr2);
} else {
console.log("[ROUND 2] Creature 2 (#" + cr2.num + ") is attacking second.");
cr1.hlt = cr1.hlt - (cr2.atk + cr1.ins);
console.log("[HIT] Creature #" + cr1.num + " health reduced to " + cr1.hlt);
if (cr1.hlt <= 0) {
console.log("[DEATH] Creature #" + cr1.num + " Eliminated");
remove(cr1);
}
}
} else {
cr1.hlt = cr1.hlt - (cr2.atk + cr1.ins);
console.log("[ROUND 1] Creature 2 (#" + cr2.num + ") is going first.");
console.log("[HIT] Creature #" + cr1.num + " health reduced to " + cr1.hlt);
if (cr1.hlt <= 0) {
console.log("[DEATH] Creature #" + cr1.num + " Eliminated");
remove(cr1);
} else {
console.log("[ROUND 2] Creature 1 (#" + cr1.num + ") is going second.");
cr2.hlt = cr2.hlt - (cr1.atk + cr2.ins);
console.log("[HIT] Creature #" + cr2.num + " health reduced to " + cr2.hlt);
if (cr2.hlt <= 0) {
console.log("[DEATH] Creature #" + cr2.num + " Eliminated");
remove(cr2);
}
}
}
I know there's probably a better way to do this, as the code in else{ } is basically the same as if{ } with some variable name changes, so, any suggestions for changes or refactoring? I'd like to improve readability and speed while accomplishing the same task as it performs currently.
Indeed you can simplify this, the general approach would be
if (cr1.ins > cr2.ins) {
[cr2, cr1] = [cr1, cr2]; // just swap them!
}
attack(cr1, cr2);
if (cr2.hlt > 0) {
attack(cr2, cr1);
}
For your logging statements with Creature 1/2 you would also need to pass through that information, so it might become something like
const a = {designator: "Creature 1", creature: cr1},
b = {designator: "Creature 2", creature: cr2};
const [first, second] = cr1.ins <= cr2.ins ? [a, b] : [b, a];
attack({attacker: first, defender: second, round: 1});
if (second.creature.hlt > 0)
attack({attacker: second, defender: first, round: 2});
Of course, if you refactor this to use an attack function as above, it might become shorter to write out the if/else again.

Can not add up variables NaN

I couldn't have the variables add up as total and neither could I make them multiply inside the var.
What am I doing wrong?
var order;
var amountsoda;
var amountbeer;
var amountwine;
var total = amountsoda + amountbeer + amountwine;
while (order != "stop") {
order = prompt("What order would you like to add? \n\n soda 2 dollar \n beer 5 dollar \n wine 10 dollar")
if (order == "soda") {
amountsoda = prompt("How much " + order + " would you like to add.");
} else if (order == "beer") {
amountbeer = prompt("How much " + order + " would you like to add.");
} else if (order == "wine") {
amountwine = prompt("How much " + order + " would you like to add.");
}
}
document.write("soda: " + amountsoda + " x 2 =" + amountsoda * 2);
document.write("<br>")
document.write("beer: " + amountbeer + " x 5 =" + amountbeer * 5);
document.write("<br>")
document.write("wine: " + amountwine + " x 10 =" + amountwine * 10);
document.write("<br>")
document.write("total: " + total);
You have to initialize the product-amounts and the total with '0'
You need to add up the total inside the while-loop depending on the product chosen
var order;
var amountsoda = 0;
var amountbeer = 0;
var amountwine = 0;
var total = 0
while (order != "stop"){
order = prompt("What order would you like to add? \n\n soda 2 dollar \n beer 5 dollar \n wine 10 dollar")
if (order == "soda" ){
amountsoda = prompt("How much " + order + " would you like to add.");
total = total + amountsoda * 2;
}
else if (order == "beer"){
amountbeer = prompt("How much " + order + " would you like to add.");
total = total + amountbeer * 5;
}
else if (order == "wine"){
amountwine = prompt("How much " + order + " would you like to add.");
total = total + amountwine * 10;
}
}
document.write ("soda: " + amountsoda + " x 2 =" + amountsoda*2);
document.write ("<br>")
document.write ("beer: " + amountbeer + " x 5 =" + amountbeer*5);
document.write ("<br>")
document.write ("wine: " + amountwine + " x 10 =" + amountwine*10);
document.write ("<br>")
document.write ("total: " + total);

Trying to make loop exit , but it currently just continues looping for 100 times

I am trying to make so when the looping of 100 hits on the character exits the loop when the life dice rolls to 0. How it currently is is all gets looped 100 times. I am not quite sure how I need to go about solving this, any tips would be helpful. My code is below.
function addChar(fname, lname, speed, agility, wep, outfit, mood) {
this.fname = fname;
this.lname = lname;
this.speed = speed;
this.agility = agility;
this.wep = wep;
this.outfit = outfit;
this.mood = mood;
this.special = function(specialMove) {
specialMove();
}
this.jumpKick = function() {
var jmpkckTimes = Math.floor(Math.random() * (100 - 33 + 1)) + 33;
document.write("He jumpkicks " + jmpkckTimes + " times. ");
if (jmpkckTimes > 70) {
document.write("He enters rage mode! ");
} else {
document.write("He does not have enough kicks for rage mode. ");
}
}
this.hits = function() {
var allHits = Math.floor(Math.random() * (100 - 33 + 1)) + 33;
document.write(" He gets attacked for " + allHits + " HP.");
}
this.lifes = function() {
var life = Math.floor(Math.random() * (3 - 0 + 1)) + 0;
if (life > 0) {
document.write(" The life dice rolls a " + life + ". You have survived! For now...");
} else {
document.write(" The life dice rolls a " + life + ". You have died!");
}
}
}
var myChar = new addChar('Johhny', 'Kicker', 10, 7, 'Ancient Greataxe', 'Barrows', 'angry');
document.write(myChar.fname + " " + myChar.lname + "'s speed is " + myChar.speed + "<br>");
document.write(myChar.fname + " " + myChar.lname + "'s agility is " + myChar.agility + "<br>");
document.write(myChar.fname + " " + myChar.lname + "'s weapon of choice is: " + myChar.wep + "<br>");
document.write(myChar.fname + " " + myChar.lname + " feels " + myChar.mood + "<br>");
document.write(myChar.fname + " " + myChar.lname + " attempts his special: ");
myChar.special(myChar.jumpKick)
for (i = 1; i < 101; i++) {
myChar.hits(myChar.allHits)
myChar.lifes(myChar.lifes)
}
function myOutfit() {
document.getElementById("demo").innerHTML = ("He is wearing " + myChar.outfit)
}
var start = Date.now();
var response = prompt("Do you think my character has what it takes?", "");
var end = Date.now();
var elapsed = (end - start) / 1000;
console.log("You took " + elapsed + " seconds" + " to type: " + response);
You need to have a way to communicate outside of the object, of what is happening inside the object.
For example, when something happens in a function, like lifes() or hits(), you should assign a value to a variable on the object to retain state. That way you can access the state from the for loop.
Example:
this.isAlive = true; // starting condition
this.lifes = function() {
var life = Math.floor(Math.random() * (3 - 0 + 1)) + 0;
this.isAlive = (life > 0);
if (this.alive) {
document.write('you survived');
} else {
document.write('you died');
}
Now in your for loop, you can access isAlive:
// loop until 100 attempts or you die, which ever comes first
for (i = 1; i < 101 && myChar.isAlive; i++) {
myChar.hits(myChar.allHits)
myChar.lifes(myChar.lifes)
}
well in general you can break out of foor loops aswell as prevent further execution of a foor loop and continue the next iteration:
for (var i = 0; i < 10; i++) {
if (i == 4) continue;
if (i == 8) break;
console.log(i);
}
this will basically print: 0, 1, 2, 3, 5, 6, 7
(as you can see it kind of skipped 4)
(it will also work in while / do while loops)
so in your case you could check if the return value of one of your functions is true or false or do some other kind of conditional checking in order to break out of the loop.
or similar to how Rob Brander wrote in his answer:
var maxTurns = 100;
var turns = 0;
while (myChar.isAlive && ++turns <= maxTurns) {
myChar.hits();
myChar.lifes();
}
console.log("character is: " + myChar.isAlive ? "alive" : "dead");
console.log("after: " + turns + " turns.");

Math.Random is not so random

I am making a basic game with popup boxes.
My problem is that if you look at the goblinAttack function it will repeat till the goblin is dead but the damage is random.
For example, I hit the goblin 6 damage every time until it dies instead of it being a random number between 1 and 25 and the goblin does 4 damage on me every time it hits. Its boring. I wanted it to be random each hit but repeating the function seems to not give a random number each time.
//VARIABLES
var dmgMultiply = Math.floor(Math.random() * 10 + 1);
var dmg = 10;
var armour = 0;
var hp = 100;
//ENEMY VARIABLES
var dmgGoblin = Math.floor(Math.random() * 10 + 1);
var goblinHP = 100;
//ARRAYS
var choiceArray = ["Type 'sword' equip your sword.",
"Type 'run' if you're scared.",
"Type 'stats' to see your stats."];
var answerArray = ["sword", "run", "stats"];
var outcomeArrayOne = ["You equip your sword.",
"You run away. Game Over."];
var outcomeArrayTwo = ["Sword Equipped."]
//GAME CHOICE
function choice(a, b, c, x, y, z, aa, bb)
{
var answer = prompt(a + "\n" + b + "\n" + c);
if(answer == x)
{
alert(aa);
swordEquipped(outcomeArrayTwo[0]);
}
if(answer == y)
{
alert(bb);
}
if(answer == z)
{
displayStats();
}
}
//EQUIPPED SWORD
function swordEquipped(a)
{
dmg = 25;
dmgMultiply = Math.floor(Math.random() * 25 + 1);
alert(a + "\n" + "DMG : " + dmg);
goblinCombatStart("goblin");
}
//GOBLIN COMBAT START
function goblinCombatStart(g)
{
alert("A wild " + g + " appears!" + "\n" + "The " + g + " has 100 HP!");
goblinAttack("goblin")
}
function goblinAttack(g)
{
alert("The " + g + " swings his axe at you!" + "\n" + "The " + g + " does " + dmgGoblin + " damage to you!");
hp -= dmgGoblin;
var attack = prompt("Type 'attack' to swing your sword at the " + g + "\n" + "HP : " + hp);
if(attack == "attack")
{
alert("You swing your sword at the " + g + "\n" + "You did " + dmgMultiply + " to the " + g);
goblinHP -= dmgMultiply;
alert("The " + g + " is on " + goblinHP + "HP");
if(goblinHP < 0)
{
goblinDead();
}
if(goblinHP > 0)
{
goblinAttack("goblin");
}
}
else
{
alert("You dropped your sword an shouted " + "'" + attack + "'" + " in the goblins face. It wasn't very effective and the goblin choppped your head off");
}
}
function goblinDead()
{
alert("You have slain the puny goblin with only a few scratches!");
}
//GAME START
choice(choiceArray[0], choiceArray[1], choiceArray[2],
answerArray[0], answerArray[1], answerArray[2],
outcomeArrayOne[0], outcomeArrayOne[1]);
//STATISTICS
function displayStats()
{
var statCheck = confirm("HP : " + hp + "\n" +
"ARMOUR : " + armour + "\n" +
"DMG : " + dmg + "\n" +
"Press OK to continue");
if(statCheck == true)
{
choice(choiceArray[0], choiceArray[1], choiceArray[2],
answerArray[0], answerArray[1], answerArray[2],
outcomeArrayOne[0], outcomeArrayOne[1]);
}
}
Instead of computing the random damage value only once at the beginning of your script, compute them whenever you need them. That would probably be in your attack function.
Maybe you are misunderstand something here: Math.random doesn't return some special magical value which changes every time it's read. It returns a number and that number doesn't change.
If you want multiple random values, you have to call Math.random multiple times. If you want a different random value whenever the goblin attacks, you have to call Math.random when it attacks.
The problem here is that you're initializing your variables at the beginning as random.
That means that, on every move, it will use the same random number that was generated at the beginning.
If you want it to be random for each time, you have to call Math.random() on every move.
As it stands, dmgMultiply and dmgGoblin are computed randomly once and use the same value on each turn, so you end up getting the same amount of damage taken and dealt each time.
Declare your variables at the beginning:
var dmgMultiply;
var dmgGoblin;
Then, set them to a random number within your attack function so that it computes a random number each turn:
function goblinAttack(g)
{
dmgMultiply = Math.floor(Math.random() * 10 + 1);
dmgGoblin = Math.floor(Math.random() * 10 + 1);
...
}
Demo

Javascript function - works in IE, not in chrome

To preface this, we are a small organization and this system was built by someone long ago. I am a total novice at javascript so I have trouble doing complicated things, but I will do my best to understand your answers. But unfortunately redoing everything from scratch is not really an option at this point.
We have a system of collecting data where clients use a login to verify a member ID, which the system then uses to pull records from an MS Access database to .ASP/html forms so clients can update their data. One of these pages has the following function that runs on form submit to check that data in fields a/b/c sum to the same total as d/e/f/g/h/i. It does this separately for each column displayed (each column is a record in the database, each a/b/c/d/e/f is a field in the record.)
The problem is with this section of the function:
for (var j=0; j<recCnt; j++) {
sumByType = milesSurf[j] + milesElev[j] + milesUnder[j];
sumByTrack = milesSingle[j] + milesDouble[j] + milesTriple[j] + milesQuad[j] + milesPent[j] + milesSex[j];
etc.
It should use javascript FOR to loop through each record and test to see if they sum to the same thing.
In Firefox and IE this is working properly; the fields sum properly into "sumByType" and "sumByTrack". You can see below I added a little alert to figure out what was going wrong:
alert(sumByType + " " + j + " " + recCnt + " " + milesSurf[j] + " " + milesElev[j] + " " + milesUnder[j]);
In Chrome, that alert tells me that the components of "sumByType" and "sumByTrack" (the various "milesXXXXX" variables) are undefined.
My question is: Why in Chrome is this not working properly, when in IE and FFox it is? Any ideas?
Full function code below:
function submitCheck(formy, recCnt) {
//2/10/03: added milesQuad
//---------------checks Q#4 that Line Mileage by type is the same as by track
var milesElev = new Array();
var milesSurf = new Array();
var milesUnder = new Array();
var milesSingle = new Array();
var milesDouble = new Array();
var milesTriple = new Array();
var milesQuad = new Array();
var milesPent = new Array();
var milesSex = new Array();
var sumByType = 0;
var milesLineTrack = new Array(); //this is for Q5 to compare it to mileage by trackage
var j = 0; var sumByTrack = 0; var liney; var yrOp;
//var str = "document.frm.milesElev" + j;
//alert(str.value);
for (var i in document.frm) {
if (i.substring(0, i.length - 1) == "milesElev") {
milesElev[parseInt(i.substring(i.length-1, i.length))] = parseFloat(document.frm[i].value); }
if (i.substring(0, i.length - 1) == "milesSurf") {
milesSurf[parseInt(i.substring(i.length-1, i.length))] = parseFloat(document.frm[i].value); }
if (i.substring(0, i.length - 1) == "milesUnder") {
milesUnder[parseInt(i.substring(i.length-1, i.length))] = parseFloat(document.frm[i].value); }
if (i.substring(0, i.length - 1) == "milesSingle") {
milesSingle[parseInt(i.substring(i.length-1, i.length))] = parseFloat(document.frm[i].value); }
if (i.substring(0, i.length - 1) == "milesDouble") {
milesDouble[parseInt(i.substring(i.length-1, i.length))] = parseFloat(document.frm[i].value); }
if (i.substring(0, i.length - 1) == "milesTriple") {
milesTriple[parseInt(i.substring(i.length-1, i.length))] = parseFloat(document.frm[i].value); }
if (i.substring(0, i.length - 1) == "milesQuad") {
milesQuad[parseInt(i.substring(i.length-1, i.length))] = parseFloat(document.frm[i].value); }
if (i.substring(0, i.length - 1) == "milesPent") {
milesPent[parseInt(i.substring(i.length-1, i.length))] = parseFloat(document.frm[i].value); }
if (i.substring(0, i.length - 1) == "milesSex") {
milesSex[parseInt(i.substring(i.length-1, i.length))] = parseFloat(document.frm[i].value); }
if (i.substring(0, i.length -1) == "milesLineTrack") {
milesLineTrack[parseInt(i.substring(i.length-1, i.length))] = document.frm[i].value; } //12/13/02 used to be parseFloat(document.frm[i].value)
if (i.substring(0,5)=="Lines") {
liney = document.frm[i].value;
if (parseInt(liney)<1 || isNaN(liney)) {
alert("Each mode must have at least 1 line. Please correct the value in question #2.");
document.frm[i].select(); return false; }}
if (i.substring(0,8)=="yearOpen") {
yrOp = document.frm[i].value;
if (parseInt(yrOp)<1825 || isNaN(yrOp)) {
alert("Please enter a year after 1825 for question #3");
document.frm[i].select(); return false; }
}
}
for (var j=0; j<recCnt; j++) {
sumByType = milesSurf[j] + milesElev[j] + milesUnder[j];
sumByTrack = milesSingle[j] + milesDouble[j] + milesTriple[j] + milesQuad[j] + milesPent[j] + milesSex[j];
//---------------to round sumByTrack and sumByType from a long decimal to a single decimal place, like frm 7.89999998 to 7.9.
sumByTrack = sumByTrack * 10;
if (sumByTrack != parseInt(sumByTrack)) {
if (sumByTrack - parseInt(sumByTrack) >= .5) {
//round up
sumByTrack = parseInt(sumByTrack) + 1; }
else { //truncate
sumByTrack = parseInt(sumByTrack); }}
sumByTrack = sumByTrack / 10;
sumByType = sumByType * 10;
if (sumByType != parseInt(sumByType)) {
if (sumByType - parseInt(sumByType) >= .5) {
//round up
sumByType = parseInt(sumByType) + 1; }
else { //truncate
sumByType = parseInt(sumByType); }}
sumByType = sumByType / 10;
//-------------end of rounding ---------------------------
if (sumByType != sumByTrack) {
if (isNaN(sumByType)) {
sumByType = "(sum of 4.a., b., and c.) "; }
else {
sumByType = "of " + sumByType; }
if (isNaN(sumByTrack)) {
sumByTrack = "(sum of 4.d., e., f., g., h., and i.) "; }
else {
sumByTrack = "of " + sumByTrack; }
alert("For #4, the 'End-to-End Mileage By Type' " + sumByType + " must equal the 'End-to-end Mileage By Trackage' " + sumByTrack + ".");
alert(sumByType + " " + j + " " + recCnt + " " + milesSurf[j] + " " + milesElev[j] + " " + milesUnder[j]);
return false;
}
//alert (milesLineTrack[j] + " " + milesSingle[j] + " " + 2*milesDouble[j] + " " + 3*milesTriple[j] + " " + 4*milesQuad[j] + " " + 5*milesPent[j] + " " + 6*milesSex[j]);
var singDoubTrip = (milesSingle[j] + 2*milesDouble[j] + 3*milesTriple[j] + 4*milesQuad[j] + 5*milesPent[j] + 6*milesSex[j])
//----------round singDoubTrip to one digit after the decimal point (like from 6.000000001 to 6.0)
singDoubTrip = singDoubTrip * 10;
if (singDoubTrip != parseInt(singDoubTrip)) {
if (singDoubTrip - parseInt(singDoubTrip) >= .5) {
//round up
singDoubTrip = parseInt(singDoubTrip) + 1; }
else { //truncate
singDoubTrip = parseInt(singDoubTrip); }}
singDoubTrip = singDoubTrip / 10;
//----------end round singDoubTrip-----------------------------------------
if (parseFloat(milesLineTrack[j]) != singDoubTrip) {
//var mlt = milesLineTrack[j];
//if isNaN(milesLineTrack[j]) { mlt =
alert("For column #" + (j+1) + ", the mainline passenger track mileage of " + milesLineTrack[j] + " must equal the single track plus 2 times the double track plus 3 times the triple track plus 4 times the quadruple track plus 5 times the quintuple track plus 6 times the sextuple track, which is " + singDoubTrip + ".");
return false;
}
}
//---------------------end of checking Q#4----------------
//return false;
}
I think for (var i in document.frm) is the problem. You should not enumerate a form element, there will be plenty of unexpected properties - see Why is using "for...in" with array iteration a bad idea?, which is especially true for array-like objects. I can't believe this works properly in FF :-)
Use this:
var ele = document.frm.elements; // or even better document.getElementById("frm")
for (var i=0; i<ele.length; i++) {
// use ele[i] to access the element,
// and ele[i].name instead of i where you need the name
}
Also, you should favour a loop over those gazillion of if-statements.

Categories