In this article, we will learn how you check that javascript arrays behave like objects and why it happens. We will be showing the key and values in the array whether you define the key or not in an array of JavaScript.
Reason for Arrays behaving like an object:
- In JavaScript, there is no real Array instead of that it behaves in an array because the Array Class has been extended from the Object Class due to which properties of an object can be used in arrays as well.
- Every Class in JavaScript except primitive data type has been extended from the object class due to which properties of an object can be used in other data types as well.
Let’s see the implementation for the above problem with an explanation as given below:
Example 1: If we will not be defining a key in the array then by default the key is set to the index of the value.
Javascript
// Initialized the array let arr = []; // push() is used to add the element in last arr.push(5); arr.push(10); arr.push( "Prince" ); arr.push( "Aditya" ); // Accessing the keys of array // using the object property let keys = Object.keys(arr).join( " " ); // Accessing the values of array // using the object property let values = Object.values(arr).join( " " ); console.log( "The keys of array is: " + keys); console.log( "The values of array is: " + values); |
Output:
The keys of array is: 0 1 2 3 The values of array is: 5 10 Prince Aditya
Example 2: In this, we will be defining the key manually and accessing the value as per the key by using the object property.
Javascript
// Initialized the array let arr = []; arr[ "neveropen" ] = "GFG" ; arr[ "Aditya" ] = "Sharma" ; arr[ "Prince" ] = "kumar" ; // Accessing the value from the array // using the object properties let value1 = arr[ "neveropen" ]; let value2 = arr[ "Aditya" ]; let value3 = arr[ "Prince" ]; console.log( "Accessing the value of neveropen: " + value1); console.log( "Accessing the value of Aditya: " + value2); console.log( "Accessing the value of Prince: " + value3); |
Output:
Accessing the value of neveropen: GFG Accessing the value of Aditya: Sharma Accessing the value of Prince: kumar