If you are an experienced developer, you may think that this question is simple, but sometimes we will find this question more interesting.
First, let’s take a look at the definition of the 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.”, Let's use objects to describe the definition of an array:
var arr = ["benjamin", "zuojj"];
//=>
var arr = {
"0": "benjamin",
"1": "zuojj"
};
Looking at the example above, I always feel that something is missing, OK, the length of the array:
var arr = {
"0" : "benjamin",
"1" : "zuojj",
"length" : 2
};
We know that in the Javascript language, an array is a special object. We can access the object's properties by accessing the array. At the same time, an array can also add properties like an object. See the following example:
var arr = {
"0" : "benjamin",
"1" : "zuojj",
"length" : 2
};
//Outputs: "benjamin"
(arr[0]);
//Outputs: 2
();
var arr = ["benjamin", "zuojj"];
= "";
//Outputs: ""
();
//Outputs: 2
();
Let’s take a look at the array methods. There are many operational methods for arrays, such as indexOf/slice/splice/sort, etc. We know that these methods actually exist in them. See the following example:
var arr = ["benjamin", "zuojj"];
//Outputs: 1
(("zuojj"));
= function(str) {
return "It is customed indexOf!";
}
//Outputs: "It is customed indexOf!"
(("zuojj"));
In fact, we can overload all array methods using objects. See the following example of push method:
var arr = {
length: 0,
push: function(val) {
//Assignment
this[] = val;
//Update the array length
+= 1;
//Return the array length
return ;
}
}
("zuojj");
("benjamin");
//Object {0: "zuojj", 1: "benjamin", length: 2, push: function}
(arr);
But there is a literal definition of an array that cannot be implemented again:
But we can use constructor instead:
If the literal definition array is not applicable, 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.