Does adding a property to an array with dot notation change it to an object?
var arr = [];
arr.something = "test";
is it an array?
I don't think so, but underscore.js says it is
console.log( _.isArray(arr) ); //true
http://jsfiddle.net/wZcyG/
If you look at the underscore.js source, you will see that the isArray
function is defined as:
_.isArray = nativeIsArray || function(obj) {
return toString.call(obj) == '[object Array]';
};
The brower's native Array.isArray
says it's an array because that's what it has been instantiated as. If the browser doesn't have a native isArray
, then underscore.js uses the second option: comparing toString
on the object to see if it matches the string [object Array]
.
Simply adding a property is not enough to change the type of the object (according to the JavaScript virtual machine, it is still an object that happens to be an array). JavaScript is a dynamic language which means that you can add properties to in-built objects, but doing so does not change what they are; you have merely extended them. For example, Prototype.js used to extend native objects by adding extra properties to them (like iterators, filters, mapping functions, etc.).
You can see the behavior in Chrome pretty easily:
> var arr = [];
arr.something = "test";
> Array.isArray(arr);
true
> toString.call(arr);
"[object Array]"
EDIT
The array doesn't lose its length
property:
> var arr = [1, 2, 3];
arr.something = "test";
console.log(arr.length, arr.something);
3 "test"
Notice that the browser reported the correct length of 3
and the correct value for test
for the something
property.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With