简体   繁体   中英

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

I'm re-learning JavaScript at the moment.

My tutor told me today that in JavaScript, "everything is an object". In fact, using a for - in loop, you can iterate over an object's properties just like you can over an array's elements.

I now have (yet another) naive question: If everything in JavaScript is an Object , why do people "bother" using Array s?

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 ). But is that the whole story? Or is there some performance gain to be had by using the built-in Array (object) data type?

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.

Simply put, an Array is an Object , but an Object is not an Array . The same is true for other types as well, such as Date , RegExp and so on.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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