Convert Object to Array?

How do I explain this? I am grabbing several elements from my document and placing them in an array, using jQuery. When I test the

typeof

this item, it returns as an Object, not an Array, which is problematic for IE. Firefox seems not to have an issue with

Object.length

, but IE won’t have any of that, so I need

Array.length

or do I? In the end, I just want IE to know how many keys are in the Array/Object…

You can test to see if an object is really an Array by using instanceof:


if ( foo instanceof Array ) {

If you have an Object (created with { } or new Object (), you can check how many keys it contains with a function like this:


function countProperties ( obj ) {
  var count = 0;
  for (var i in obj) {
    count++
  }
  return count;
}

If you are selecting your elements with jQuery, you can use length on your jQuery object.


var $foos = $("p > .foo");

// All jQuery objects have a length property.
alert($foos.length);

// Alternatively, you can use the size() method.
alert($foos.size());

Well, the HTMLCollection object has a built in length property, so that isn’t just jQuery magic. :slight_smile:

I have tried the suggestions above and none seem to get it working in IE, here is the code

http://www.roberthenrylowe.com/lab/jQuery/codeconverter.css

You’ll see that the code works properly in Firefox, but not in IE.

Does this help?


<script type="text/javascript">
Array.prototype.isItAnArray = true; // give this property only to real arrays

function getLength(thing) {
	if (typeof thing == "object" && !thing.isItAnArray) {
		var count = 0;
		for (var test in thing) {
			count++;
		}
		return count;
	} else {
		return thing.length;
	}
}

window.onload = function () {
	var myArray = new Array(1,2,3,4,5);
	
	var myObject = new Object();
	myObject.test1 = 1;
	myObject.test2 = 2;
	myObject.test3 = 3;
	myObject.test4 = 4;
	myObject.test5 = 5;
	
	alert(getLength(myArray));
	alert(getLength(myObject));
}
	
</script>

It turns out that I incorrectly assumed that Internet Explorer included ’
’ newlines in a multi-line string. Now I am trying to figure out how to detect line breaks, any ideas?

Relevant code can be found here: