手写系列 —— Array数组常用API


添加元素,一律返回数组新的长度,删除元素一律返回删除的元素。(会改变自身)

1.数组方法会改变自身

push

Array.prototype.myPush = function() {
    for( let i = 0 ; i < arguments.length ; i++){
        this[this.length] = arguments[i] ;
    }
    return this.length;
}

let arr = ['Jerry', 'Tom'];
arr.myPush('buliangc', 'double');
console.log(arr);	// [ 'Jerry', 'Tom', 'buliangc', 'double' ]

unshift

Array.prototype.myUnshift = function () {
    var arrLength = this.length;
    var arr = this;
    for (let i = arrLength + arguments.length - 1; i >= 0; i--) {
        if (i > arguments.length - 1) {
            arr[i] = arr[i - arguments.length];
        } else {
            arr[i] = arguments[i];
        }
    }
    return arr.length
}

let arr = ['Jerry', 'Tom'];
arr.myUnshift('buliangc', 'double');
console.log(arr);	// [ 'buliangc', 'double', 'Jerry', 'Tom' ]

pop

Array.prototype.myPop = function () {
    var arr = this;
    if (arr.length === 0) return undefined;
    var result = arr[this.length - 1];
    this.length = this.length - 1;
    return result;
}

let arr = ['Jerry', 'Tom'];
let res = arr.myPop();
console.log(arr, res);	// [ 'Jerry' ] Tom

splice

在这里插入代码片

shift

Array.prototype.myShift = function () {
    var arr = this;
    if (arr.length === 0) return undefined;
    var firstRes = arr[0];
    for (let i = 1; i < arr.length; i++) {
        arr[i - 1] = arr[i];
    };
    this.length = this.length - 1;
    return firstRes;
}

let arr = ['Jerry', 'Tom', 'f', 'g', 'j'];
let res = arr.myShift();
console.log(arr, res);	// [ 'Tom', 'f', 'g', 'j' ] Jerry

reverse

Array.prototype.myReverse = function () {
    var arr = this;
    var arrLength = arr.length;
    var copyArr = Array.from(arr);
    for (let i = 0; i < arrLength; i++) {
        console.log(copyArr[i]);
        arr[arrLength - i] = copyArr[i];
    }
    return arr;
}

let arr = ['Jerry', 'Tom', 'f', 'g', 'j'];
let res = arr.myReverse();
console.log(arr, res);	// [ 'Jerry', 'j', 'g', 'f', 'Tom', 'Jerry' ] [ 'Jerry', 'j', 'g', 'f', 'Tom', 'Jerry' ]

copyWithin

Array.prototype.myCopyWithin = function (target, start, end = this.length) {
    let arr = this;
    for (let i = start; i < end; i++) {
        arr[target] = arr[i];
        target++;
    }
    return arr;
}

let arr = ['a', 'b', 'c', 'd', 'e'];

arr.myCopyWithin(0, 3, 4);	// ["d", "b", "c", "d", "e"]
arr.myCopyWithin(1, 3);	// [ 'd', 'd', 'e', 'd', 'e' ]
console.log(arr);

fill

Array.prototype.myFill = function (value, start = 0, end = this.length) {
    let arr = this;
    for (let i = start; i < end; i++) {
        arr[i] = value;
    }
    return arr;
}

let arr = [1, 2, 3, 4];

arr.myFill(0, 2, 4);
console.log(arr);	// [ 1, 2, 0, 0 ]
arr.myFill(5, 1);
console.log(arr);	// [ 1, 5, 5, 5 ]
arr.myFill(6);
console.log(arr);	// [ 6, 6, 6, 6 ]


2.数组方法不会改变自身

concat

Array.prototype.myConcat = function () {
    let arr = this;
    for (let i = 0; i < arguments.length; i++) {
        for (let j = 0; j < arguments[i].length; j++) {
            arr[this.length] = arguments[i][j];
        }
    }
    return arr;
}

let arr = ['Jerry', 'Tom'];
let arr1 = ['Kitty', 'Monkey', 'Dog', 'Cat'];
let arr2 = ['A', 'B', 'N', 'M'];
let res = arr.myConcat(arr1, arr2);
console.log(arr);	// ['Jerry','Tom','Kitty','Monkey','Dog','Cat','A','B','N','M']

slice

Array.prototype.mySlice = function (start, end = this.length) {
    let arr = this;
    let res = [];
    if (start < 0) {
        for (let i = start + end; i < end; i++) {
            res.push(arr[i])
        }
    } else {
        for (let i = start; i < end; i++) {
            res.push(arr[i])
        }
    }

    return res;
}

let arr = [1, 2, 3, 4, 5, 6];

let res = arr.mySlice(-4);
console.log(arr, res);	// [ 1, 2, 3, 4, 5, 6 ] [ 3, 4, 5, 6 ]

indexOf

Array.prototype.myIndexOf = function (num) {
    let arr = this;
    for (let i = 0; i < arr.length; i++) {
        if (arr[i] == num) {
            return i
        }
    }
    return -1;
}

let arr = [1, 2, 3, 4, 5, 6];

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

lastIndexOf

Array.prototype.myLastIndexOf = function (num) {
    let arr = this;
    for (let i = arr.length; i >= 0; i--) {
        if (arr[i] == num) {
            return i
        }
    }
    return -1;
}

let arr = [1, 2, 3, 4, 5, 2, 6];

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

join

Array.prototype.myJoin = function (separator = ',') {
    let arr = this;
    let str = '';
    for (let i = 0; i < arr.length; i++) {
        str += arr[i];
        if (i != arr.length - 1) {
            str += separator;
        }
    }
    return str;
}

let arr = [1, 2, 3, 4, 5, 2, 6];

let res = arr.myJoin('_');
console.log(arr, res);	// 1_2_3_4_5_2_6

toString

Array.prototype.myToString = function (separator = ',') {
    let arr = this;
    let str = '';
    for (let i = 0; i < arr.length; i++) {
        str += arr[i];
        if (i != arr.length - 1) {
            str += separator;
        }
    }
    return str;
}

let arr = [1, 2, 3, 4, 5, 2, 6];
let arr1 = [1, 2, 'a', '1a']
let res = arr1.myToString();
console.log(arr, res);		// 1,2,a,1a

3. 循环遍历方法

forEach


Array.prototype.myForEach = function (fn, thisArg) {
    let arr = this;
    for (let i = 0; i < arr.length; i++) {
        fn.call(thisArg, arr[i]);
    }
}
let obj = {
    num: 10
}
let arr = [1, 2, 3, 4, 5, 6];
arr.myForEach(function (value, index, arr) {
    console.log(value + this.num);
}, obj);
console.log(arr);

map

filter

Array.prototype.myFilter = function (fn) {
    let arr = this;
    let res = [];
    for (let i = 0; i < arr.length; i++) {
        if (fn(arr[i], i, arr)) {
            res.push(arr[i]);
        }
    }
    return res;
}

let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
let res = arr.myFilter((value, index, arr) => {
    return value > 4;
});
console.log(arr, res); // [1, 2, 3, 4, 5, 6, 7, 8, 9] [ 5, 6, 7, 8, 9 ]

every

Array.prototype.myEvery = function (fn) {
    let arr = this;
    let count = 0;
    for (let i = 0; i < arr.length; i++) {
        if (fn(arr[i])) {
            count++;
        }
    }
    if (count == arr.length) {
        return true;
    } else {
        return false;
    }
}

let arr = [5, 6, 5, 8];
let res = arr.myEvery((value) => {
    return value > 4;
});
console.log(arr, res);	// [ 5, 6, 5, 8 ] true

some

Array.prototype.mySome = function (fn) {
    let arr = this;
    let count = 0;
    for (let i = 0; i < arr.length; i++) {
        if (fn(arr[i])) {
            count++;
        }
    }
    if (count >= 1) {
        return true;
    } else {
        return false;
    }
}

let arr = [1, 2, 3, 4, 5, 6];
let res = arr.mySome((value) => {
    return value > 4;
});
console.log(arr, res);	// [ 1, 2, 3, 4, 5, 6 ] true

reduce

Array.prototype.myReduce = function(fn, initValue) {
    var arr = this;
    var currentIndex = arguments.length === 1? 1: 0;
    var currValue = arguments.length === 1 ? arr[0] : initValue;
    for(let i = currentIndex; i< arr.length; i++){
        currValue = fn(currValue, arr[i])
    }
    return currValue;
}

let arr = [1, 2, 3, 4, 5];

let result = arr.myReduce((preVal, nextVal) => {
    return preVal + nextVal;
}, 1);

console.log(result);

总结

手写数组api帮助我更好的理解这些方法的实现方式。同时也加深了印象。但是部分数组api的手写方法,都是简单版本的,并没有考虑到所有的情况,仅供参考使用。

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值