Javascript 数组是原语吗?字符串?对象?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5048371/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Are Javascript arrays primitives? Strings? Objects?
提问by Jared Farrish
Are arrays merely objects in disguise? Why/why not? In what way(s) are they (such/not)?
数组只是伪装的对象吗?为什么/为什么不?他们以什么方式(这样/不)?
I have always thought of arrays and objects in JS as essentially the same, primarily because accessing them is identical.
我一直认为 JS 中的数组和对象本质上是相同的,主要是因为访问它们是相同的。
var obj = {'I': 'me'};
var arr = new Array();
arr['you'] = 'them';
console.log(obj.I);
console.log(arr.you);
console.log(obj['I']);
console.log(arr['you']);
Am I mislead/mistaken/wrong? What do I need to know about JS literals, primitives, and strings/objects/arrays/etc...?
我是否误导/错误/错误?关于 JS 文字、原语和字符串/对象/数组/等,我需要了解什么?
Are arrays/objects merely strings in disguise? Why/why not? In what way(s) are they (such/not)?
数组/对象只是伪装的字符串吗?为什么/为什么不?他们以什么方式(这样/不)?
回答by ?ime Vidas
Arrays are objects.
数组是对象。
However, unlike regular objects, arrays have certain special features.
但是,与常规对象不同,数组具有某些特殊功能。
Arrays have an additional object in their prototype chain - namely
Array.prototype. This object contains so-called Array methods which can be called on array instances. (List of methods is here: http://es5.github.com/#x15.4.4)Arrays have a
lengthproperty (which is live, ergo, it auto-updates) (Read here: http://es5.github.com/#x15.4.5.2)Arrays have a special algorithm regarding defining new properties (Read here: http://es5.github.com/#x15.4.5.1). If you set a new property to an array and that property's name is a sting which can be coerced to an integer number (like
'1','2','3', etc.) then the special algorithm applies (it is defined on p. 123 in the spec)
数组在其原型链中有一个额外的对象——即
Array.prototype. 这个对象包含所谓的 Array 方法,可以在数组实例上调用。(方法列表在这里:http: //es5.github.com/#x15.4.4)数组有一个
length属性(它是实时的,因此,它会自动更新)(在这里阅读:http: //es5.github.com/#x15.4.5.2)数组有一个关于定义新属性的特殊算法(阅读此处:http: //es5.github.com/#x15.4.5.1)。如果你设置一个新的属性到一个数组和属性的名称是可以强制转换为一个整数刺(如
'1','2','3',等),那么特殊算法应用(它是在规范中定义第123页)
Other than these 3 things, arrays are just like regular objects.
除了这三件事,数组就像普通对象。
Read about arrays in the spec: http://es5.github.com/#x15.4
阅读规范中的数组:http: //es5.github.com/#x15.4
回答by Matti Virkkunen
Objects are an unordered map from string keys to values, arrays are an ordered list of values (with integer keys). That's the main difference. They're both non-primitive, as they're composed of multiple values, which also implies pass-by-reference in JavaScript.
对象是从字符串键到值的无序映射,数组是值的有序列表(带有整数键)。这是主要的区别。它们都是非原始的,因为它们由多个值组成,这也意味着 JavaScript 中的按引用传递。
Arrays are also a kind of object, though, so you can attach extra properties to them, access their prototype and so on.
不过,数组也是一种对象,因此您可以为它们附加额外的属性,访问它们的原型等等。
In your revised example, you're only taking advantage of the fact that an array is actually an object, i.e. you can set any property on them. You shouldn't do that. If you don't need an ordered list of values, use a plain object.
在您修改后的示例中,您只是利用了数组实际上是一个对象这一事实,即您可以对它们设置任何属性。你不应该那样做。如果您不需要值的有序列表,请使用普通对象。
回答by aiham
Strings can be either primitive or objects, depending on how they were declared.
字符串可以是原始类型,也可以是对象,这取决于它们的声明方式。
var str = 'yes';
Gives you a primitive, while,
给你一个原始的,而,
var str = new String('yes');
will give you a String object.
会给你一个 String 对象。
All arrays are the same (Whether or not they were defined with [] or new Array()), are of the type object and inherit from the "Array" object's prototype. There aren't real classes in Javascript, everything is an object, and there's a system defined object called Array. It has a property called 'prototype' (of type object), and when you use the new keyword on an object with a prototype property, it creates an instance with a reference to the contents of the prototype and stores it in your variable. So all arrays you've ever used in Javascript are objects and instances of Array's prototype property.
所有数组都是相同的(无论它们是否用 [] 或 new Array() 定义),都是 object 类型并继承自“Array”对象的原型。Javascript 中没有真正的类,一切都是对象,并且有一个系统定义的对象,称为 Array。它有一个名为“prototype”(对象类型)的属性,当您在具有原型属性的对象上使用 new 关键字时,它会创建一个引用原型内容的实例并将其存储在您的变量中。因此,您在 Javascript 中使用过的所有数组都是 Array 原型属性的对象和实例。
In any case, although arrays really are objects, they behave like arrays because of their useful properties and functions (Such as length, slice, push etc).
在任何情况下,尽管数组确实是对象,但由于其有用的属性和功能(例如长度、切片、推送等),它们的行为类似于数组。
Another note, although I said there are no classes, when you do this:
另一个注意事项,虽然我说没有类,但当你这样做时:
console.log(Object.prototype.toString.call(your_object));
it will give you a string in the form [object Object]. But what's useful is that when you call it with an array, you get [object Array] same with functions which give [object Function] and a number of other system defined types, which assists in differentiating between normal objects and arrays (Since the typeof operator will always just return the string 'object').
它会给你一个 [object Object] 形式的字符串。但有用的是,当你用数组调用它时,你得到的 [object Array] 与给出 [object Function] 的函数和许多其他系统定义的类型相同,这有助于区分普通对象和数组(因为 typeof运算符将始终只返回字符串“对象”)。
Try this
试试这个
var a = Array;
and go into firebug and examine the contents of a, especially it's 'prototype' property.
并进入萤火虫并检查 a 的内容,尤其是它的“原型”属性。
Edit:Changed the wording a bit, to be more correct. In fact when you use the new keyword, it creates an instance which referencesthe prototype object. So any changes made to the prototype after the instance's declaration, will still affect the instance.
编辑:稍微改变了措辞,使其更正确。事实上,当您使用 new 关键字时,它会创建一个引用原型对象的实例。因此,在实例声明后对原型所做的任何更改仍将影响实例。
Edit:In answer to your latest revised question (are arrays/objects actually strings in disguise): No. They are objects, as I've explained. Strings are either a primitive type, or an object type (An instance of the String object) which contains the primitive equivalent as one of it's properties.
编辑:回答您最新修订的问题(数组/对象实际上是伪装的字符串):不。正如我所解释的,它们是对象。字符串要么是基本类型,要么是对象类型(字符串对象的一个实例),其中包含基本等价物作为其属性之一。
回答by slifty
Arrays are not primitives in Javascript, they are objects. The key difference is that as a result, when you pass an array to a function it is passed by reference, not by value.
数组不是 Javascript 中的基元,它们是对象。关键的区别在于,因此,当您将数组传递给函数时,它是按引用传递的,而不是按值传递的。
So yes! Arrays are objects in javascript, with a full blown Array.prototype and everything (don't touch that though...)
所以是的!数组是 javascript 中的对象,具有完整的 Array.prototype 和所有内容(尽管不要碰它...)
The confusion comes from the fact that javascripts lets you access object attributes in two ways:
混淆来自这样一个事实,即 javascripts 允许您通过两种方式访问对象属性:
myObj.attribute or myObj["attribute"]
myObj.attribute 或 myObj["attribute"]
Really what makes an array an array has nothing to do with the way you store data -- any object can store values using the syntax you use to store the array -- what makes an array an array is the fact that array methods (e.g. shift() and sort()) are defined for Array.prototype.
真正使数组成为数组的原因与您存储数据的方式无关——任何对象都可以使用您用来存储数组的语法来存储值——使数组成为数组的原因是数组方法(例如 shift () 和 sort()) 是为 Array.prototype 定义的。
回答by connrs
Trying to be brief with what I believe to be of the most significance: arrays have a number of methods that objects do not. Including:
试图简要介绍我认为最重要的内容:数组具有许多对象没有的方法。包括:
- length
- push
- pop
- 长度
- 推
- 流行音乐
An object declared as var x = {foo:bar}has no access to a .length() method. They are both objects but with the array as a sort of superset with methods mentioned as above.
声明为的对象var x = {foo:bar}无法访问 .length() 方法。它们都是对象,但数组是一种具有上述方法的超集。
I don't feel I this is even close to being of Crockford standard in terms of explanation but I'm trying to be succinct.
我不觉得我在解释方面甚至接近 Crockford 标准,但我试图简洁。
If you want to get some quick results, open up Firebug or your javascript Console and try Array.prototype and Object.prototype to see some details
如果您想快速获得结果,请打开 Firebug 或您的 javascript 控制台并尝试 Array.prototype 和 Object.prototype 以查看一些详细信息
Update:In your example you declare an array and then do:
更新:在您的示例中,您声明一个数组,然后执行以下操作:
foo['bar'] = 'unexpectedbehaviour';
will produce unexpected results and won't be available in simple loops such as:
将产生意想不到的结果,并且在简单的循环中不可用,例如:
var foo=[0,1];
foo['bar'] = 2;
for(var i=0;i<foo.length;i++){
console.log(foo[i]);
}
//outputs:
//0
//1
An array can accept foo['bar']=xor foo.bar=ylike an object but won't necessarily be available to be looped through as highlighted above.
数组可以接受foo['bar']=x或foo.bar=y喜欢一个对象,但不一定可以像上面突出显示的那样循环遍历。
Not that I'm saying that you can't iterate through the properties of an object, just that when working with an Array, you're utilising that unique functionality and should remember not to get confused.
我并不是说您不能遍历对象的属性,只是在使用 Array 时,您正在利用这种独特的功能,并且应该记住不要混淆。
回答by James Sumners
In JavaScript you have a few types, everythingelse is an object. The types in JavaScript are: boolean, number, and string. There are also two special values, "null" and "undefined".
在JavaScript中你有几个类型,一切其他都是对象。JavaScript 中的类型是:boolean、number 和 string。还有两个特殊值,“null”和“undefined”。
So the quest "is a JavaScript array an object?" is slightly ambiguous. Yes, a JavaScript array is an "object" but it is not an instance of "Object". A JavaScript array is an instance of "Array". Although, all objects inherit from Object; you can view the inheritance chain on the MDC. Additionally, arrays have slightly different properties than an object. Arrays have the .lengthproperty. They also have the .slice(), .join(), etc methods.
所以这个问题“JavaScript 数组是一个对象吗?” 有点模棱两可。是的,JavaScript 数组是一个“对象”,但它不是“对象”的实例。JavaScript 数组是“Array”的一个实例。虽然,所有对象都继承自 Object;您可以在 MDC上查看继承链。此外,数组与对象的属性略有不同。数组具有.length属性。他们也有.slice(),.join()等方法。
Douglas Crockford provides a nice surveyof the language's features. His survey discusses the differences you are asking about. Additionally, you can read more about the difference between literals and constructorsin question #4559207.
Douglas Crockford对该语言的特性进行了很好的调查。他的调查讨论了您所询问的差异。此外,您可以阅读有关问题 #4559207 中文字和构造函数之间差异的更多信息。
回答by Jeff Hubbard
Arrays are Objects, but of a specialized nature. Objects are collections of values indexed by keys (in Javascript notation, {'key': 'value'}), whereas Arrays are Objects whose keys are numeric (with a few functions and properties). The key difference between them is obvious when you use a for eachloop--an Object will iterate over all the values in its properties, whereas an Array will return the keys instead. Here'sa link to a JSFiddle demonstrating the difference--notice that the first for each, which uses an array, returns the indexes, not the values; in contrast, the second for eachreturns the actual values at those keys.
数组是对象,但具有特殊的性质。对象是由键索引的值的集合(在 Javascript 符号中{'key': 'value'}),而数组是键是数字的对象(具有一些函数和属性)。当您使用for each循环时,它们之间的主要区别很明显——对象将迭代其属性中的所有值,而数组将返回键。这是一个指向 JSFiddle 的链接,演示了不同之处——请注意,第一个for each使用数组的返回索引,而不是值;相反,第二个for each返回这些键的实际值。

