JavaScript handwritten code fifth issue (rewrite array method 1) - the method that can change the original array

1. Why write code by hand?

In the daily development process, we often take it out and use it directly, never thinking about the underlying implementation logic of the code, but when I started to study some underlying things, I began to understand the underlying implementation ideas of each method and function in JavaScript , I think this can improve our code level and logical thinking very well.

2. Implement the array method by hand

2.1 push

push adds elements from the back and returns the length of the array after the push is complete

2.1.1 Basic use

            let arr = [1, 2];
            console.log(arr.push(1, 2, 3)); // 5
            console.log(arr); // [1,2,1,2,3]

2.1.2 Handwritten implementation

Array methods on the array's prototype object

            Array.prototype.myPush = function () {
    
    
                for (let i = 0; i < arguments.length; i++) {
    
    
                    // this就是调用该方法的数组arr,
                    // 数组当前最后一项的索引为 this.length - 1,再往后面加索引就为this.length
                    this(this.length) = arguments[i]
                }
                return this.length
            };

call test
print normally

            console.log(arr.myPush(1, 2, 3)); // 5
            console.log(arr); //  [1,2,1,2,3]

2.2 pop

Delete the last element of the array and return the deleted element. This method changes the length of the array.

2.2.1 Basic use

            let arr = [1, 2, 3];
            console.log(arr.pop()); // 3
            console.log(arr); // [1,2]

2.2.2 Handwritten implementation

            Array.prototype.myPop = function () {
    
    
                let result = this[this.length - 1];
                this.length = this.length - 1;
                return result;
            };
            console.log(arr.myPop()); // 3
            console.log(arr); // [1,2]

2.3 shift

Removes the first element from the array and returns the value of that element. This method changes the length of the array.

2.3.1 Basic use

            let arr = [1, 2, 3];
            console.log(arr.shift()); // 1
            console.log(arr); // [2,3]

2.3.2 Handwritten implementation

            Array.prototype.myShift = function () {
    
    
                let result = this[0];
                for (let i = 0; i < this.length; i++) {
    
    
                    // 后面的元素依次赋给前一项
                    // 因为数组的第一个元素已经删除
                    this[i] = this[i + 1];
                }
                // 改变数组长度
                this.length--;
                // 返回被删除的元素
                return result;
            };
            console.log(arr.myShift()); // 1
            console.log(arr); // [2,3]

2.4 unshift

Adds one or more elements to the beginning of an array and returns the new length of the array.

2.4.1 Basic use

			let arr = [1, 2, 3];
            console.log(arr.unshift(4, 5)); // 5
            console.log(arr); // [4,4,1,2,3]

2.4.2 Handwritten implementation

            Array.prototype.myUnshift = function () {
    
    
                // 最终数组的长度sum = 原数组长度 + unshift传入的参数的个数
                let sum = this.length + arguments.length;
                for (let i = sum; i > 0; i--) {
    
    
                    // 如果还没往后遍历到传入的参数的时候
                    // 原数组的值依次往向后赋值
                    if (i > arguments.length) {
    
    
                        this[i - 1] = this[i - 1 - arguments.length];
                    } else {
    
    
                        this[i - 1] = arguments[i - 1];
                    }
                }
                return sum;
            };
            console.log(arr.myUnshift(4, 5)); // 5
            console.log(arr); // [4,5,1,2,3]

2.5 splice

2.5.1 Basic use

The splice() method is used to add or remove elements from the array. will change the original array.
grammar:

array.splice(index,howmany,item1,.....,itemX)

The first parameter index : required. Specifies where elements are added/removed from.
The second parameter howmany : optional. Specifies how many elements should be removed. Must be a number, but can be "0".
Subsequent parameters : optional. the new element to add to the array

Example of use
No parameters are passed in, no operation is performed, [] is returned, and the original array does not change

            let arr = [1, 2, 3, 4];
            console.log(arr.splice()); // []
            console.log(arr); //  [1, 2, 3, 4]

Pass in a parameter index to delete the element after index 1 , and the original array changes

            let arr = [1, 2, 3, 4];
            console.log(arr.splice(1)); // [2,3,4]
            console.log(arr); // [1]

Pass in two parameters index howmany, delete 2 elements from index 0

            let arr1 = [1, 2, 3, 4];
            console.log(arr1.splice(0, 2)); // [1,2]
            console.log(arr1); // [3,4]

Pass in three parameters index how many other parameters, delete 2 elements from index 0, and replace them with the following parameters.

            let arr2 = [1, 2, 3, 4];
            console.log(arr2.splice(0, 2, 5, 6)); // [1,2]
            console.log(arr2); // [5,6,3,4]

2.5.2 Handwritten implementation

           Array.prototype.mySplice = function (index, num, ...args) {
    
    
                let newArr = [];
                let returnArr = [];
                // 如果没有传入参数,直接返回空数组
                if (index == undefined || num == 0) return [];
                if (index < 0) index = index + this.length;
                // 如果没有传入截取数组的长度,自己手动计算
                if (!num) {
    
    
                	// 这里是将num转换为索引值,方便后续的遍历
                    num = this.length - index + 1;
                } else if (num > 0) {
    
    
                    num = num + index;
                }
                // 遍历index之前的数组,赋给newArr
                for (let i = 0; i < index; i++) {
    
    
                    newArr.push(this[i]);
                }
                // 遍历我们要删除的数组范围
                for (; index < num; index++) {
    
    
                    returnArr.push(this[index]);
                }
                // 如果传入其他参数,就传入的参数添加进去
                if (args.length > 0) {
    
    
                    newArr.push(...args);
                }
                // 遍历num后面的数组,赋给newArr
                for (let i = num; i < this.length; i++) {
    
    
                    newArr.push(this[i]);
                }
                // newArr 是我们想要的原数组的值
                for (let i = 0; i < newArr.length; i++) {
    
    
                    this[i] = newArr[i];
                }
                // 截取长度
                this.length = newArr.length;
                return returnArr;
            };
            console.log(arr.mySplice());
            console.log(arr.mySplice(1)); // [2,3,4]
            console.log(arr); // [1]
            let arr1 = [1, 2, 3, 4];
            console.log(arr1.mySplice(0, 0)); // [1,2]
            console.log(arr1); // [3,4]

            let arr2 = [1, 2, 3, 4];
            console.log(arr2.mySplice(0, 2, 5, 6)); // [1,2]
            console.log(arr2); // [5,6,3,4]

2.6 fill

2.6.1 Basic use

The fill() method is used to replace elements of an array with a fixed value .
grammar:

array.fill(value, start, end)

The first parameter value : required. The filled value.
The second parameter start : optional. Start filling the position.
The third parameter end : optional. Stop padding position (defaults to array.length)

Example of use

    		let arr = [1, 2, 3, 4];
            console.log(arr.fill(4));
            console.log(arr); // [4, 4, 4, 4]
            arr.fill(5, 0, 2);
            console.log(arr); // [5, 5, 4, 4]
            console.dir(Array.prototype);

2.6.2 Handwritten implementation

            Array.prototype.myFill = function (value, start = 0, end = this.length) {
    
    
                if (start && start < 0) start = this.length + start;
                if (end && end < 0) end = this.length + end;
                for (; start < end; start++) {
    
    
                    this[start] = value;
                }
                return this;
            };
            console.log(arr.fill(4));
            console.log(arr); // [4, 4, 4, 4]
            arr.fill(5, 0, 2);
            console.log(arr); // [5, 5, 4, 4]

2.7 reverse

2.7.1 Basic use

The reverse() method is used to reverse the order of the elements in the array.

            let arr = [1, 2, 3, 4, 5];
            arr.reverse();
            console.log(arr); // [5, 4, 3, 2, 1]

2.7.2 Handwritten implementation

            Array.prototype.myReverse = function () {
    
    
                let len = this.length - 1;
                for (let i = 0; i < Math.floor(this.length / 2); i++) {
    
    
                    // 交换这两个元素位置
                    let temp = arr[i];
                    arr[i] = arr[len];
                    arr[len--] = temp;
                }
                return this;
            };
            arr.myReverse();
            console.log(arr); // [5, 4, 3, 2, 1]

2.8 sort

2.8.1 Basic use

The sort() method is used to sort the elements of an array.
The sort order can be alphanumeric or ascending or descending .
The default sort order is ascending alphabetically .
This method mutates the original array !

This is just to sort the numbers . If you have specific ideas, you can discuss them in the comment area
. Use examples

            let arr = [1, 3, 2, 4];
            arr.sort((a, b) => b - a);
            console.log(arr); // [4,3,2,1]

2.8.2 Handwritten implementation

Refactoring using bubble sort.

            Array.prototype.mySort = function (callback) {
    
    
                // 使用了冒泡排序
                for (let i = 0; i < this.length - 1; i++) {
    
    
                    for (let j = 0; j < this.length - 1 - i; j++) {
    
    
                        if (callback(this[j], this[j + 1]) > 0) {
    
    
                            let temp = this[j];
                            this[j] = this[j + 1];
                            this[j + 1] = temp;
                        }
                    }
                    return this;
                }
            };
            arr.mySort((a, b) => a - b);
            console.log(arr);

2.9 copyWithin

2.9.1 Basic use

The copyWithin() method is used to copy elements from a specified location of an array to another specified location of an array.
grammar:

array.copyWithin(target, start, end)

The first parameter target : required. Copy to the specified target index location.
The second parameter start : optional. The starting position for element copying. The default starting position is 0
The third parameter end : optional. The index position at which to stop copying (defaults to array.length). If it is a negative value, it means the reciprocal.

Example usage:
Copy the first two elements of the array to the third and fourth positions:

            let arr = [1, 2, 3, 4, 5];
            arr.copyWithin(2, 0, 2);
            console.log(arr); // [1, 2, 1, 2, 5]

2.9.2 Handwritten implementation

            Array.prototype.myCopyWithin = function (target, start = 0, end = this.length) {
    
    
                let newArr = [];
                if (target < 0) target = this.length + target;
                if (start < 0) start = this.length + start;
                if (end < 0) end = this.length + end;
                for (let i = start; i < end; i++) {
    
    
                    newArr.push(this[i]);
                }
                let arrLength = newArr.length;
                let k = 0;
                // 同时判断赋值的区间和待拷贝数组的长度的大小
                let len = arrLength < this.length - target ? target + arrLength : this.length;
                for (; target < len; target++) {
    
    
                    console.log(newArr[k]);
                    this[target] = newArr[k++];
                }
                return this;
            };
Welcome everyone to discuss and study, thank you for your support

Guess you like

Origin blog.csdn.net/qq_63299825/article/details/131353732