Phony Arrays
JavaScript does not have real arrays. That isn't all bad. JavaScript's arrays are really easy to use. There is no need to give them a dimension, and they never generate out-of-bounds errors. But their performance can be considerably worse than real arrays.
The typeof
operator does not distinguish
between arrays and objects. To determine that a value is an array, you also need to
consult its constructor property:
if (Object.prototype.toString.apply(my_value) === '[object Array]'){ // my_value is truly an array! }
That test will give a false negative if an array was created in a different frame or window. This test is more reliable when the value might have been created in another frame:
if (my_value && typeof my_value === 'object' && typeof my_value.length === 'number' && !(my_value.propertyIsEnumerable('length')) { // my_value is truly an array! }
The arguments
array is not an array; it is an
object with a length
member. These tests will not
identify the arguments array as an 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.