I am attending a surprise party tonight and have a wedding to attend this weekend, so this will be a short post today.
In my recent post, Batch Function, I introduce a technique that can be used to turn arguments into Arrays. You use the Slice Function attached to the prototype of Array to convert Array-like objects into Arrays. For example:
// arguments var getArgumentsAsArray() { return Array.prototype.slice.call(arguments, 0); } // nodelist var getElementsByTagName(el, tagName) { return Array.prototype.slice.call(el.getElementsByTagName(tagName), 0); }
Mostly, I use this this technique to reduce elements from the front of a collection, by change the 0
to the first index in the collection that I want. However, I recently realized that IE 6 does not support this technique on nodeLists (childNodes and lists returned by getElementsByTagName()
). In fact it will break you JavaScript code and throw an exception.
I played with various techniques to see if there was another Hack that worked for IE, but nothing did. In the end I came up with this x-browser safe function:
var convertToArray(obj, n) { if (! obj.length) {return [];} // length must be set on the object, or it is not iterable var a = []; try { a = Array.prototype.slice.call(obj, n); } // IE 6 and posssibly other browsers will throw an exception, so catch it and use brute force catch(e) { Core.batch(obj, function(o, i) { if (n <= i) { a[i - n] = o; } }); } return a; };
Where n
is the number of elements you want to skip. So, if I want to skip the first two elements of the collection, then "n = 2", and if I do not want to skip any, then "n = 0".