Reputation:
The following script prints undefined to the console for each character in the string, but works correctly in Chrome.
<script>
function main()
{
var x = "hello world";
for ( var i = 0; i < x.length; ++i ) {
console.log( x[i] );
}
}
main();
</script>
Do I have to do something to the array in order to get this to work properly in all browsers?
Upvotes: 3
Views: 1709
Reputation: 1
If you use the following code, try to increase TimeOut value to maximum...
window.setTimeOut('Your Js function(), 150)
Now, it increase to
window.setTimeOut('Your Js function(), 2000)
Upvotes: -1
Reputation: 34407
It's console
the problem here. This object does not exist in IE Javascript engine.
If you do this it works in both
<script>
function main()
{
var x = "hello world", result = "";
for ( var i = 0; i < x.length; ++i )
result += x[i];
document.write(result); //it prints "hello world" on page
}
main();
</script>
EDIT:
console
object does not exists until IE10 (as correctly noted by Cerbrus, unless you turn on the IE developer tool, in such case it exists also on IE8)[]
to access strings chars can be used in IE8+ (on IE7 it does not work yet)Upvotes: -1
Reputation: 272096
The []
is supported in some browsers but not all:
Array-like character access (the second way above) is not part of ECMAScript 3. It is a JavaScript and ECMAScript 5 feature.
For maximum compatibility, use String.charAt()
instead:
<script>
function main()
{
var x = "hello world";
for ( var i = 0; i < x.length; ++i ) {
console.log( x.charAt(i) );
}
}
main();
</script>
Upvotes: 5
Reputation: 72857
Older versions of IE don't support the array notation (string[x]
) to access strings, use: charAt()
instead.
<script>
function main() {
var x = "hello world";
for ( var i = 0; i < x.length; ++i ) {
console.log( x.charAt(i) );
}
}
main();
</script>
Also, if you're directly executing your function, you could as well create a self-executing anonymous function (to preserve the scope / not pollute the global namespace)
<script>
(function main() {
var x = "hello world";
for ( var i = 0; i < x.length; ++i ) {
console.log( x.charAt(i) );
}
}());
</script>
Unless you have to run it from somewhere else also, of course.
Upvotes: 2