ok, I've added an IF to filter out the properties I don't want and added some more alerts() to see what is going on at each stage.
There is something strange going on here and I am starting to think this has something to do with the way prototype objects/functions work which I don't understand yet.
What is really strange to me is that in this snippet
Code:
//build the sorted array
var sortedArray = new Array();
for(var i=0; i < keys.length; i++) {
//alert(keys[i]); //this alert outputs values - aaa, bbb, ccc
sortedArray[keys[i]] = this[keys[i]];
}
the alert() outputs the expected c orrect values
but immediately below this loop this debugging snippet
Code:
//this for loop is for debugging only
for(var i in sortedArray) {
alert(i); ////this alert outputs values - aaa, bbb, ccc, sortAssoc
}
outputs as above but with the additional element with key = 'sortAsscoc'.
It appears to me that no matter what code logic I use, something in javascript is appending prototype name and code to my array.
If you have a few minutes, I would appreciate it if you could have a look at the latest full test code below with the alerts() and their ouputs in comments next to them and see if you can makes sense of what is happening here.
Thank you again for your help.
Code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script type="text/javascript">
/**********************************************
Prototype to sort an associative array
***********************************************/
Array.prototype.sortAssoc = function() {
//separate the keys into an array
var keys = new Array();
for(var i in this) {
//alert(i); //this alert outputs values - bbb, aaa, ccc, sortAssoc
if(i != 'sortAssoc') {
//alert(i); //this alert outputs values - bbb, aaa, ccc
keys.push(i);
}
}
//now sort the keys
keys.sort();
//build the sorted array
var sortedArray = new Array();
for(var i=0; i < keys.length; i++) {
//alert(keys[i]); //this alert outputs values - aaa, bbb, ccc
sortedArray[keys[i]] = this[keys[i]];
}
//this for loop is for debugging only
for(var i in sortedArray) {
alert(i); ////this alert outputs values - aaa, bbb, ccc, sortAssoc
}
return sortedArray;
}
//***** testing code **************
var myArray = [];
myArray['bbb'] = 'b_red';
myArray['aaa'] = 'a_green';
myArray['ccc'] = 'c_blue';
//sort the above array
var arraySorted = [];
arraySorted = myArray.sortAssoc();
//display the results
for(var i in arraySorted) {
document.write(i+" = "+arraySorted[i]+'<br /><br />');
}
</script>
</head>
<body>
</body>
</html>
Bookmarks