Changing an array to an object (uppercase) by adding a value with a dot

Does a property add to the array with point notation its change to an object?

var arr = []; arr.something = "test"; 

is an array?

I don’t think so, but underscore.js says it

 console.log( _.isArray(arr) ); //true 

http://jsfiddle.net/wZcyG/

+7
javascript
source share
1 answer

If you look at the source of underscore.js, you will see that the isArray function isArray defined as:

  _.isArray = nativeIsArray || function(obj) { return toString.call(obj) == '[object Array]'; }; 

The growth brower Array.isArray says it is an array because it is what it was created. If the browser does not have a native isArray , then underscore.js uses the second option: comparing toString with an object to see if it matches the string [object Array] .

Just adding a property is not enough to change the type of an object (according to the JavaScript virtual machine, it is still an object that is an array). JavaScript is a dynamic language that means you can add properties to inline objects, but that does not change them; you just expanded them. For example, Prototype.js is used to expand your own objects by adding additional properties to them (such as iterators, filters, display functions, etc.).

You can pretty easily see the behavior in Chrome:

 > var arr = []; arr.something = "test"; > Array.isArray(arr); true > toString.call(arr); "[object Array]" 

EDIT

The array does not lose the length property:

 > var arr = [1, 2, 3]; arr.something = "test"; console.log(arr.length, arr.something); 3 "test" 

Note that the browser reported the correct length of 3 and the correct value for test for the something property.

+7
source share

All Articles