This article describes how to merge concat with JavaScript simulated arrays. For more information, see
Task:First, I defined a variable var arr = [0, 1, 2, 3, 4, 5]. Now I want to simulate the push method to add something after 5 of this array. What should we do? I will give you five minutes to think about it. Please do not look down before thinking.
Analysis:We want to add something to the end of the array, right? The key point is how we can find the final position of the element. Let's not consider the last position first. Let's first think about how we access the content of an array at ordinary times. Is it like this? arr [n], right, if we access an index greater than this array, It is undefined. In short, it is undefined without this index, if we keep adding 1 to the index of this array, if undefined appears, is it the position we are looking for? Although this method works, I have a better way to use the length attribute, the length attribute can obtain the length of this array. The length is the index + 1 of this array, and we just want to add content to this index.
Code:
Var arr = [,]; arr. length gets the last position of this array
Task: Now that we get the last position of the array, we can add content to it. How can we add it? Who to add and how to add.
Analysis: Now let's look back at how to add content to an array? The length obtained is the position to be added.
Merging:
var arr = [0,1,2,3,4,5];function Push(value){arr[arr.length] = value;}Push(6);console.log(arr); //[0, 1, 2, 3, 4, 5, 6]
Task: although you can add only one content to it now, what should you do?
Analysis: I miss my old friend for. If this old friend can help us with repeated tasks, please ask him for help.
Code:
Analysis: How should we write this? What is I less? How many digits do we add? So how many digits do we need to add? It seems that we do not know, but an old friend knows that it is arguments. It can get the input parameters and it is a pseudo array, this means that it can also use the length attribute like an array to obtain the length of the input real parameter.
Code:
For (var I = 0; IAnalysis: Now the question is, where can we add the content and return to our task? Do we want to add the content we passed in at the last position of an array, for what we wear in, how can we get the content we pass in? We seem to have said that arguments can get its content.
Code:
Var arr = [0, 1, 2, 3, 4, 5]; function Push {for (var I = 0; IComplete.
Extra-curricular Extension: Basic friends
OK, although the task has been completed, the problem is that this code can only serve the array of arr, if we want to provide this function for the Array, we need to add this method to the Array prototype.
Var arr = [0, 1, 2, 3, 4, 5]; Array. prototype. Push = function {for (var I = 0; IModify the arr to this, which indicates who calls it. If you want to know