changing an array to an Object (upper case) by adding a value using a dot

时光毁灭记忆、已成空白 提交于 2019-12-08 17:40:24

问题


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/


回答1:


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.



来源:https://stackoverflow.com/questions/17845488/changing-an-array-to-an-object-upper-case-by-adding-a-value-using-a-dot

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!