I’m rather confused at the moment, could someone explain this one to me? Maybe it’s something small I’m oblivious to, but I’m confused as to why this isn’t resulting as I expect it to.
I have created a samples to show the issue I’m seeing…
var dataString = "abc";
document.write(" This is a test ... " + "<br/>")
for (i in dataString ) {
document.write("<br/> +" + dataString[i] + ": ")
for (k in dataString ) {
document.write(" ="+dataString[k] +", ");
}
}
Now, my results in Chrome are:
This is a test ...
+a:
+b:
In FireFox are: (This is the result I expected)
This is a test ...
+a: =a, =b, =c,
+b: =a, =b, =c,
+c: =a, =b, =c,
Results in IE8 are:
This is a test ...
Can anyone explain to me what’s happening here? Have I missed something critical?
Note:
You can translate strings to arrays across browsers using "abc".split("") as per this example, just remember that this is no longer a string and now if you output it, it will be output as an array a,b,c
It is not part of the JavaScript standard(*) that strings should have their characters accessible as numbered properties; this is an extension originally introduced by Mozilla. Consequently
dataString[i]will beundefinedon older browsers including IE<8.To access a character in a string properly you should use
charAt.For the same reason,
for...inover a string won’t iterate over the indexes in all browsers.And even if it did, it would be the wrong thing to use, because
for...inis for enumerating properties in anObject({}) map, not iterating over sequences.for...inshould not be used on anArrayorStringas you will get all the members of that instance, not just numeric-indexed ones, and there’s no guarantee you will get them in any particular order.For
ArrayandStringthe correct loop is the old-schoolfor iloop. And you should usevareven if it’s a global variable.(*: well… not in ECMAScript Third Edition. The new Fifth Edition states that Strings have ‘array index names’, which might be an endorsement of this feature. Seems a little unclear)