This is the 26th day of my participation in Gwen Challenge
preface
I wrote two previous articles about arrays:
-
Simulate the implementation of array additions
-
Array traversal large summary
This article will simulate the implementation of the core array method, is a supplement to the above two articles, but also the array knowledge of the final supplement!
Simulate the implementation of the core method
For the sake of memorization, I’ve divided them into two categories:
Let’s start implementing it one at a time
Methods that can change the original array
1. push()
role
Use to add one or more elements to the end of an array and return the length of the array after adding the new elements
Analog implementation
Array.prototype._push = function(){
for(var i=0; i<arguments.length; i++){this[this.length] = arguments[i];
}
return this.length;
}
//test code
var arr = [1.2.3];
console.log(arr._push(4.5));/ / 5
console.log(arr)/ / [1, 2, 3, 4, 5]
Copy the code
2. pop()
role
Used to delete the last element of the array and return that element; Equivalent to shearing
Analog implementation
Array.prototype._pop = function () {
if (this.length) {
var result = this[this.length - 1]
delete this[this.length];
this.length--;
returnresult; }}//test code
var arr = [1.2.3.4]
console.log(arr._pop());/ / 4
console.log(arr);/ / [1, 2, 3]
console.log(arr.length);/ / 3
Copy the code
3. unshift()
role
Use to add one or more elements to the beginning of an array and return the length of the array after adding the new elements
Analog implementation
Array.prototype._unshift = function () {
// Move the original elements of the array behind
for (var i = this.length - 1; i >= 0; i--) {
this[i + arguments.length] = this[i];
}
// The elements to be added are added one by one to the empty space
for (var j = 0; j < arguments.length; j++) {
this[j] = arguments[j];
}
return this.length;
}
var arr = [1.2.3]
console.log(arr._unshift('a'.'b'.'c'));/ / 6
console.log(arr);/ / / 'a', 'b', 'c', 1, 2, 3]
console.log(arr.length);/ / 6
Copy the code
4. shift()
role
Use to delete the first element of an array and return that element. It’s the same as a pop
Analog implementation
Array.prototype._shift=function(){
var res = this[0];
// Make the first digit equal to the second digit, covering the first digit.
for(var index in this) {this[index-1] = this[index]
}
return res;
}
//test code
var arr = [1.2.3]
console.log(arr.shift());/ / 1
console.log(arr);/ / [2, 3]
console.log(arr.length);/ / 2
Copy the code
5. reverse()
role
Used to reverse the order of the elements in an array and return the changed array
Analog implementation
Array.prototype._reverse = function () {
var left = 0;// Store the first position on the left
var right = this.length - 1;// Store the last position on the right
while (left < right) {// Stop the process
var temp = this[left];// Use an intermediate variable to swap positions
this[left] = this[right];
this[right] = temp; left++; right--; }}var arr = [1.2.3.4.5.6.7]
console.log(arr._reverse());//undefined
console.log(arr);// [7, 6, 5, 4, 3, 2, 1]
Copy the code
6. splice()
role
Intercept and add, return the intercepted portion; Add Adds new data to the original array at the notch
The format is as follows: arr.splice(starting from the number of bits, cut length, add data 1, data 2 at the cut…) ;
By default, starting with o, the array is truncated to.length-1 bits
Analog implementation
Array.prototype._splice = function (start = 0, leng = this.length, ... data) {
if (this.length) {
let res = []
let j = 0
// Find the data to be returned and save the res
for (let i = start; j < leng; i++, j++) {
res.push(this[i]);
}
// Add data to the gap
// Find the first half
let beforeArr = []
for (let i = 0; i < start; i++) {
beforeArr.push(this[i]);
}
// Find the second half
let afterArr = []
for (let i = start + leng; i < this.length; i++) {
afterArr.push(this[i]);
}
// Finally the current array becomes the clipped result
let newThis = [...beforeArr,...data,...afterArr]
// this = newThis ~~~~~~~~~
// Return the clipped data res
return res
}
}
let a = [1.2.3.4.5.6.7.8]
let b = [1.2.3.4.5.6.7.8]
console.log(a.splice(1.2.'a'.'b'),a);
console.log(b._splice(1.2.'a'.'b'),b);
Copy the code
7. sort()
role
Used to sort the members of a group and return the current sorted array
Analog implementation
Array.prototype._sort = function (fn) {
// Consider the case without fn
debugger
let temp
for (var i = 0; i < this.length; i++) {
for (var j = i+1; j < this.length; j++) {
if (this[i] > this[j]) {
temp = this[j]
this[j] = this[i]
this[i] = temp; }}}return this
}
console.log([1.2.5.1.9.3.1].sort());//[1, 1, 1, 2, 3, 5, 9]
console.log([1.2.5.1.9.3.1]._sort());//[1, 1, 1, 2, 3, 5, 9]
Copy the code
Methods that do not change the original array
1. concat()
role
Merges two or more arrays to form a new array and returns the new array
Analog implementation
Array.prototype._concat = function(. args){
// Copy the current array
let res = [...this]
for (let i = 0; i < args.length; i++) {
// Get the array args[I];
if(args[i].length){
for (let index = 0; index < args[i].length; index++) { res.push(args[i][index]); }}}return res
}
let a = [1.2]
let b = [1.2]
console.log(a.concat(['x'.'y']),a);//[1, 2, "x", "y"] [1, 2]
console.log(b._concat(['x'.'y']),b);//[1, 2, "x", "y"] [1, 2]
Copy the code
2. slice()
role
To truncate an array, pass two arguments indicating the number of bytes to truncate, and return the truncated portion. The default argument is from bit 0 to last
Analog implementation
Array.prototype._slice = function(start = 0,end=this.length){
let res = []
for (let i = start; i < end; i++) {
res.push(this[i]);
}
return res
}
console.log([1.2.3.4.5].slice(1.3))/ / [2, 3]
console.log([1.2.3.4.5].slice(1.3))/ / [2, 3]
Copy the code
3. join()
role
Used to concatenate array elements into a string. Returns the string. Elements are separated by passing arguments as specified delimiters, and are joined by “,” if not
Analog implementation
Array.prototype._join = function () {
let res = ' '
let temp = arguments.length ? arguments[0] : ', ';
for (let i = 0; i < this.length; i++) {
if(i<this.length-1){
res += (this[i]+temp);
}else{
res += this[i]
}
}
return res
}
console.log([1.2.3].join());/ / 1, 2, 3
console.log([1.2.3]._join());/ / 1, 2, 3
Copy the code
4. toString()
role
A string used to return arrays. Undefined and null are considered empty, and nested arrays will be flattened regardless of how many layers
Analog implementation
Array.prototype._toString=function(){
let res = ' '
for (let i = 0; i < this.length; i++) {
if(Array.isArray(this[i])){
_toString(this[i])
}else{
if(i<this.length-1){
res +=this[i].toString()+', '
}else{
res +=this[i].toString()
}
}
}
return res
}
console.log(['a'.'b'.'c'].toString());//a,b,c
console.log(['a'.'b'.'c']._toString());//a,b,c
Copy the code
END
This is the core array method simulation implementation!
The real implementation may be different from what I wrote, but it doesn’t matter, as long as we are familiar with what these methods do, we have achieved the purpose of this study!
If you have any questions or suggestions, please leave a message. Thank you!