If you're an experienced developer, you might think this is a relatively simple problem, but sometimes we feel it's more interesting.
First, let's look at the definition of the array:"An array is just a list of values which can are accessed by using an integer as the" key. The list starts at 0 and goes up from there., we use objects to describe the definition of an array:
Copy Code code as follows:
var arr = ["Benjamin", "ZUOJJ"];
=>
var arr = {
"0": "Benjamin",
"1": "ZUOJJ"
};
Look at the example above, the total feeling is missing what, OK, the length of the array:
Copy Code code as follows:
var arr = {
"0": "Benjamin",
"1": "ZUOJJ",
"Length": 2
};
We know that in the JavaScript language, an array is a special object, and we can access the object's properties by accessing the array, and the array can also add properties like an object. Look at the following example:
Copy Code code as follows:
var arr = {
"0": "Benjamin",
"1": "ZUOJJ",
"Length": 2
};
Outputs: "Benjamin"
Console.log (Arr[0]);
Outputs:2
Console.log (arr.length);
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 look at the array method, the array has many operable methods, such as Indexof/slice/splice/sort, we know actually these methods exist in the Array.prototype. Look at the following example:
Copy Code code as follows:
var arr = ["Benjamin", "ZUOJJ"];
Outputs:1
Console.log (Arr.indexof ("ZUOJJ"));
Arr.indexof = function (str) {
Return "It is customed indexof!";
}
Outputs: "It is customed indexof!"
Console.log (Arr.indexof ("ZUOJJ"));
In fact, we can use objects to overload all of the array methods. Look at the following example of the push method:
Copy Code code as follows:
var arr = {
length:0,
Push:function (val) {
assigning values
This[this.length] = val;
Update array length
This.length + 1;
Returns the length of an array
return this.length;
}
}
Arr.push ("Zuojj");
Arr.push ("Benjamin");
Object {0: "Zuojj", 1: "Benjamin", Length:2, push:function}
Console.log (arr);
But there is one that cannot be implemented anew, the literal definition of an array:
Copy Code code as follows:
var arr = ["Benjamin", "ZUOJJ"];
But we can use constructors instead:
Copy Code code as follows:
var arr = new Array ("Benjamin", "ZUOJJ");
If the literal definition array is not applied, then we can redefine the definition of the array in our own way.
Copy Code code as follows:
var Myarr = new Customarray ("Benjamin", "ZUOJJ");
Now you know how the array works in JavaScript, and hopefully it will help.