Welcome to WebmasterWorld Guest from 23.20.137.66

Forum Moderators: open

Message Too Old, No Replies

Help for a newbie JavaScript student

     
9:06 am on Jul 17, 2008 (gmt 0)

5+ Year Member



I've just started learning JavaScript and I'm already stumped. I have this code:

var mytest1 = new String();
mytest1.setNumber( 2 );

var mytest2 = new String();
mytest2.setNumber( 3 );

if( mytest1 + mytest2 == 5 ) alert('Success!');

But nothing is happening when I run it! What am I missing or doing wrong? Help would be much appreciated. I'm sure it's something stupid.

Thanks all,
Hannah

9:48 am on Jul 17, 2008 (gmt 0)

10+ Year Member



Hi,

setNumber is no standard method for strings in javascript.

HTH, Tom

10:09 am on Jul 17, 2008 (gmt 0)

5+ Year Member



Thanks for your reply. What should I use instead?
10:09 am on Jul 17, 2008 (gmt 0)

10+ Year Member



Hannahb, welcome to WebmasterWorld!

mytest1 and mytest2 are declared as strings, adding like you did will not result in a value of 5 but in a string with value "23".

if( mytest1 + mytest2 == "23" ) alert('Success!');

That will probably work (I didn't check however)

10:09 am on Jul 17, 2008 (gmt 0)

5+ Year Member



Or is the use of "String" the problem?
10:11 am on Jul 17, 2008 (gmt 0)

5+ Year Member



Hi adb64. Thanks for your answer. I tried changing to "23", but that didn't work either. Just a blank screen. :(
10:29 am on Jul 17, 2008 (gmt 0)

10+ Year Member



Hi Hannahb,
I've tried and check javascript string object and like Arno_Adams (AKA Tom) mentions, setNumber is not a method for the string object.
What exactly do you want to achieve?
10:32 am on Jul 17, 2008 (gmt 0)

5+ Year Member



It's for an assignment for my class. Maybe it would be best to post the original question.

Write the missing implementation of Test to make this code work and the
alert appear:

var mytest1 = new Test();
mytest1.setNumber( 2 )

var mytest2 = new Test();
mytest2.setNumber( 3 );

if( mytest1 + mytest2 == 5 ) alert('Success!')

11:22 am on Jul 17, 2008 (gmt 0)

5+ Year Member



Hi,

You need to override the Object class's valueOf method.
Like this:

function Test(){
this.number;
this.setNumber = function(number){
this.number = number;
}
this.valueOf = function(){
return this.number;
}
}

The valueOf method tells the JavaScript interpreter how to convert the object into a primitive, in this case a Test object into an int.

Core JavaScript 1.5 Reference:Global Objects:Object:valueOf - MDC [developer.mozilla.org]

Andrew

[edited by: Little_G at 11:26 am (utc) on July 17, 2008]

11:25 am on Jul 17, 2008 (gmt 0)

5+ Year Member



It worked! Thank you so much! :)
 

Featured Threads

Hot Threads This Week

Hot Threads This Month