JavaScript objects used as hybrid data structures

I have pretty decent JavaScript knowledge and prototype inheritance, which is used to initialize data structures, but I'm still not quite sure how one of the unique JS functions works.

Suppose I create an array:

var myArr = []; 

Now I can move the elements to an array:

 myArr.push('foo'); myArr.push('bar'); 

At this time, myArr.length == 2

Now from there I can do something like

 myArr['myProp'] = 5; // OR myArr.myProp = 5; 

But my myArr.length is still 2, and I can use some type of iterative method to iterate over the 2 values โ€‹โ€‹that were originally ported.

Thus, basically this object is a โ€œhybridโ€ data structure that can be processed as an array or object.

So my question is the syntax of the native object ( myObj.someProperty = 'blah' OR myObj['someProperty'] = 'blah' ), apply specifically to the Object.prototype and therefore ANY inherited from this prototype? This makes sense, since the prototype chain of the object looks like this:

 var myObj = {} -> Object.prototype -> null 

And the array prototype chain looks like this:

 var myArr = [] -> Array.prototype -> Object.prototype -> null 

To make me assume that everything you can do with an object ( myObj.someProperty //as getter or setter ) can be done using an array, which will then explain the phenomena that I mentioned above.

+4
source share
1 answer

To fill out my answer. This is certainly true. Prohibition of literals and temporal values โ€‹โ€‹almost everything in JavaScript is an object. Including functions, arrays and variables.

It is for this reason that it is considered that iteration is considered dangerous for iterating through an array with syntax:

 for (x in myArray){} 

The above line of code can lead to unpredictable results!

This approach of creating all types of data as objects allows JavaScript to be as dynamic and flexible as it is.

You can see the full description of Object here .

+2
source

All Articles