Confusion
A common error in JavaScript programs is to use an object when an array is required or an array when an object is required. The rule is simple: when the property names are small sequential integers, you should use an array. Otherwise, use an object.
JavaScript itself is confused about the difference between arrays and objects. The
typeof
operator reports that the type of an
array is 'object'
, which isn't very
helpful.
JavaScript does not have a good mechanism for distinguishing between arrays and
objects. We can work around that deficiency by defining our own is_array
function:
var is_array = function (value) { return value && typeof value === 'object' && value.constructor === Array; };
Unfortunately, it fails to identify arrays that were constructed in a different window or frame. If we want to accurately detect those foreign arrays, we have to work a little harder:
var is_array = function (value) { return Object.prototype.toString.apply(value) === '[object Array]'; };
Get JavaScript: The Good Parts now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.