通过使用点添加值将数组更改为Object(大写) [英] changing an array to an Object (upper case) by adding a value using a dot
问题描述
使用点表示法向数组添加属性是否将其更改为对象?
Does adding a property to an array with dot notation change it to an object?
var arr = [];
arr.something = "test";
它是一个数组吗?
I不这么认为,但是underscore.js说它是
I don't think so, but underscore.js says it is
console.log( _.isArray(arr) ); //true
推荐答案
如果你看一下underscore.js 来源,您会看到 isArray
函数被定义为:
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]';
};
浏览器的原生 Array.isArray
表示它是一个数组,因为它是被实例化的。如果浏览器没有本机 isArray
,则underscore.js使用第二个选项:比较 toString
对象,看它是否匹配字符串 [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]
.
简单地添加属性不足以改变对象的类型(根据JavaScript虚拟机,它仍然是恰好是数组的对象)。 JavaScript是一种动态语言,这意味着您可以向内置对象添加属性,但这样做并不会改变它们的内容;你只是扩展了他们。例如,Prototype.js用于通过向它们添加额外属性来扩展本机对象(如迭代器,过滤器,映射函数等)。
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.).
您可以看到行为在Chrome中非常容易:
You can see the behavior in Chrome pretty easily:
> var arr = [];
arr.something = "test";
> Array.isArray(arr);
true
> toString.call(arr);
"[object Array]"
编辑
数组不会丢失长度
属性:
> var arr = [1, 2, 3];
arr.something = "test";
console.log(arr.length, arr.something);
3 "test"
请注意,浏览器报告了正确的长度 3
以及测试
的某些
属性的正确值。
Notice that the browser reported the correct length of 3
and the correct value for test
for the something
property.
这篇关于通过使用点添加值将数组更改为Object(大写)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!