简体   繁体   English

为什么在JavaScript中有数组? 反对不足吗?

[英]Why are there Arrays in JavaScript? Don't Objects suffice?

I'm re-learning JavaScript at the moment. 目前,我正在重新学习JavaScript。

My tutor told me today that in JavaScript, "everything is an object". 我的老师今天告诉我,在JavaScript中,“一切都是对象”。 In fact, using a for - in loop, you can iterate over an object's properties just like you can over an array's elements. 实际上,使用for - in循环,可以像遍历数组元素一样遍历对象的属性。

I now have (yet another) naive question: If everything in JavaScript is an Object , why do people "bother" using Array s? 现在,我还有另一个幼稚的问题:如果JavaScript中的所有内容都是Object ,为什么人们使用Array “生”?

My first guess is there must be methods on Array that aren't available on Object (which a quick and superficial glance at MDN seems to confirm), and Array s can be indexed (ie myArray[i] ) (and have a length ). 我的第一个猜测是Array上必须有一些在Object上不可用的方法(这似乎证明了MDN的快速而肤浅的印象),并且Array可以被索引(即myArray[i] )(并且具有length )。 。 But is that the whole story? 但这是整个故事吗? Or is there some performance gain to be had by using the built-in Array (object) data type? 还是使用内置的Array (对象)数据类型可以获得一些性能提升?

Arrays are an object type. 数组一种对象类型。 (as are functions, object etc). (以及函数,对象等)。

They have internal counter and push and pop states among other things. 它们具有内部计数器以及推入和弹出状态。 And they have many uses (to keep collections of data for one). 而且它们有许多用途(将数据收集保存为一个)。

If you really want to reimplement that kol hakavod (go right ahead). 如果您真的想重新实现该功能 ,请继续。

It is a fun project though to try to re-implement a js array on your own. 尽管尝试自己重新实现js数组,但这是一个有趣的项目。

Simply put, an Array is an Object , but an Object is not an Array . 简而言之, ArrayObject ,但Object 不是 Array The same is true for other types as well, such as Date , RegExp and so on. 其他类型也是如此,例如DateRegExp等。

You could strip the language of many native features and still have the exact same solution scope boundaries (you could solve the exact same set of problems), but you'd repeat yourself over and over implementing very basic objects. 您可以剥离许多本机功能的语言,并且仍然具有完全相同的解决方案范围边界(可以解决一组完全相同的问题),但是您会一遍又一遍地实现非常基本的对象。 Additionally, different code bases would use different implementations of these types and you'd loose compatibility and interoperability. 此外,不同的代码库将使用这些类型的不同实现,您将失去兼容性和互操作性。

Having certain types natively implemented makes using the language easier, more robust, more explicit and more performant. 在本机实现某些类型后,使用该语言将变得更轻松,更健壮,更明确更高效。

On top of all that, languages as a whole (and JavaScript in particular) strive to conform to well known practices - it makes adopting the language easier and porting existing code simpler and faster. 最重要的是,整个语言(尤其是JavaScript)努力遵循众所周知的惯例-它使采用该语言变得更加容易,并使现有代码的移植变得越来越简单。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM