Easy. Strings and arrays share much in common. They both have length and indexes. Though there are probably other similarities, those two are what's important here. However, there was a time when the indexes of a string weren't available using the square bracket notation:
Code:
var nums = phone[number];
I'm not sure when each individual browser started to allow it. But obviously IE started with version 8. There are other approaches to solve this, but since all browsers allow square bracket index notation for arrays, we can simply convert the string to an array using the split method:
Code:
<!DOCTYPE HTML>
<html xmlns='http://www.w3.org/1999/xhtml'>
<head>
<meta charset='UTF-8' />
</head>
<body>
<div id="container"></div>
<script src='js/jquery.js'></script>
<script>
var phone = "22223333444455556666".split('');
$(function(){
for (number=0;number<20;number++){
var nums = phone[number];
$("div#container").append("<div class='n"+nums+"'></div>");
}
});
</script>
</body>
</html>
Problem solved!
Note: number in the above is an undeclared global variable and though a different case (I think that's what saves you) is the name of a javascript global object (Number). Taking that into consideration, along with the general best practices idea of not having any variables in the global scope if they are not required, and being more sensitive to valid HTML 5, I would do something more like:
Code:
<!DOCTYPE html>
<html>
<head>
<title>Phone Numbers</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script src='js/jquery.js'></script>
<script>
$(function(){
var phone = "22223333444455556666".split(''), num;
for (num=0;num<20;num++){
var nums = phone[num];
$("div#container").append("<div class='n"+nums+"'></div>");
}
});
</script>
</head>
<body>
<div id="container"></div>
</body>
</html>
Bookmarks