If you are an experienced developer, you may think this question is relatively simple, but sometimes, we find this question more interesting.
First let’s take a look at the definition of an array: “An array is just a list of values which can be accessed by using an integer as the “key”. The list starts at 0 and goes up from there.” , below we use objects to describe the definition of arrays:
Looking at the above example, I always feel that something is missing, OK, the length of the array:
We know that in the Javascript language, an array is a special object. We can access the properties of the object using the method of accessing the array. At the same time, the array can also add properties like an object. Look at the following example:
var arr = ["benjamin", "zuojj"];
arr.url = "www.jb51.net";
//Outputs: "www.jb51.net"
console.log(arr.url);
//Outputs: 2
console.log(arr.length);
Let’s take a look at the methods of arrays. Arrays have many operable methods, such as indexOf/slice/splice/sort, etc. We know that these methods actually exist in Array.prototype. Look at the example below:
In fact, we can overload all array methods using objects. See the push method example below:
But there is one thing that cannot be re-implemented, the literal definition of an array:
But we can use constructor instead:
If a literal definition of an array does not apply, then we can redefine the definition of the array in our own way.
Now you know how arrays work in JavaScript, I hope it will be helpful to everyone.