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...
Sample 1
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 happ开发者_开发知识库ening 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
for (i in dataString ) {
document.write("<br/> +" + dataString[i] + ": ")
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 be undefined
on older browsers including IE<8.
To access a character in a string properly you should use charAt
.
For the same reason, for...in
over 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...in
is for enumerating properties in an Object
({}
) map, not iterating over sequences. for...in
should not be used on an Array
or String
as 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 Array
and String
the correct loop is the old-school for i
loop. And you should use var
even if it's a global variable.
document.write(' This is a test ... <br/>');
for (var i= 0; i<dataString.length; i++) {
document.write('<br/> +'+dataString.charAt(i)+': ');
for (var k= 0; k<dataString.length; k++) {
document.write(' ='+dataString.charAt(k)+', ');
}
}
(*: 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)
according to W3C :
The for...in statement loops through the elements of an array or through the properties of an object.
Your dataString as a string
type and nothing else, the result you have is interpreted differently on each browser.
- IE : dataString isn't an object : > "I don't loop" (not obvious, datatype doesn't match)
- FF : dataString is a ??? : "I iterate on each character, both and combine it" (very obvious)
- Chrome : dataString is an array of character : "I iterate on each character". (not obvious because a string can be considered as a character array, but still...)
Obvious but still normal.
精彩评论