quote:
Originally posted by Flippy
I see, so it has to do with type conversion.
That's one more thing I don't really understand about this language, types... Is it just me or is every variable of type 'var'? And you don't need to specify any type (int, string, etc) in function arguments either, or what kind of type your function returns.
Correct. And this is the same in VBScript and JavaScript btw.
But even in C#, VB, etc you have that kind of type, usually it is called a Variant.
However, although JScript has a very loose type convention (which can be handy, but also prone to user errors), you can define variables as a specific type using the New operator. In fact, to be more correct, you actually define the variable as an object of a certain type. So your variable actually becomes an object. eg:
var myBoolean = new boolean();
However, the moment you start comparing normal variables, JScript internally converts the variables to the proper types. Hence the existance and difference between equality and identity operators.
In fact, you actually provided a nice example yourself to explain it. See below (the fine print):
-----------------------------
Anywyas, in regards to your reg. expression:
quote:
Originally posted by Flippy
jscript code:
function startsWithToken(orig)
{
return (orig.match(/^\$\$/) == "$$")
}
function endsWithToken(orig)
{
return (orig.match(/^\$\$$/) == "$$")
}
Now, the startsWith function works fine, but the endsWith method does not...
Because you actually check if the string is exactly "$$", nothing more, nothing less. This because you have the
^ in there (meaning 'from the beginning'). So, the correct expression is:
jscript code:
function endsWithToken(orig)
{
return (orig.match(/\$\$$/) == "$$")
}
PS: in regards to the identity and equality issue. Here we use == instead of === because match actually returns an array, and you compare it to a string. So these are two different types.
If you would use === then the comparisson would always return false because the two things you compare are of a different type (internaly).
Using == makes that JScript internally first converts everything to a string (in this case). Thus it first converts the array to a string prior to comparing. When doing so, it simply takes the first array element disgarding all the rest and converts that into a string.
But better would be using the
test method instead. Because that does not require the internal reg. exp. object to update, it doesn't need to create and populate an array, and already returns a boolean (so JScript doesn't need to converts types either). And thus it also runs a lot faster:
jscript code:
function startsWithToken(orig)
{
return /^\$\$/.test(orig)
}
function endsWithToken(orig)
{
return /\$\$$/.test(orig)
}