Forum Moderators: open

Message Too Old, No Replies

Grr @ JS!

Just some tedious problems

         

ahmedtheking

1:21 pm on Sep 23, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Can someone just tell me what's wrong here:

checkvals = "4-4-3";

checkvals = checkvals.split('-');
var counter = new Number;

for (x = 0; x < checkvals.length; x++) {
num = checkvals[x];
counter -= num;
}

document.write(counter+"<br />");
document.write(counter.replace(/-/, ""));

(in case you're wondering why i've used '-=' instead of '+=', well my stupid browser (FF that is) seems to put the numbers together instead of adding them up!)

eelixduppy

10:10 pm on Sep 23, 2006 (gmt 0)



Try something like this:

checkvals = "4-4-3";

checkvals = checkvals.split('-');
var counter = 0;

for (x = 0; x < checkvals.length; x++) {
num = parseInt(checkvals[x]);
counter += num;
}
document.write(counter+"<br />");

Since the numbers were in a string format, they were concatenated instead of added.

Good luck!

DrDoc

10:21 pm on Sep 23, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



That's the downside about JavaScript and its non-typed variables, along with identical syntax for addition and concatenation. I have found that it is always best to ensure that the string/number is exactly what I expect it to be (i.e. a string or a number) ... by utilizing parseInt (or multiply by 1, in case you also work with floating point numbers) or force an empty string onto the end of what I expect to be in string format.

ahmedtheking

11:46 pm on Sep 23, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



I've had to use that parseInt! Instead, what I did was keep the -= and then compared the amount in the counter to the amount submitted by the user! JS can be so lame!

eelixduppy

12:24 am on Sep 24, 2006 (gmt 0)



>>>JS can be so lame!

It can be annoying at times, however, it is something us web programmers cannot live without ;)