JS array method handwritten code implementation (2)

It’s not easy to write by hand. If it helps you, please give me a free like ૮₍♡>..< ₎ა

1. JavaScript Array toString() method

Definition and usage

toString()Method returns a string containing all array values, separated by commas.

Note: toString()Method does not modify the original array.

parameter

No parameters.

Native js handwritten implementation:

    var arr = [12, 15, 25, 36, 88]
    var arr1 = [16]
    var arr2 = ["ni","hao","jian","jian"]
    Array.prototype.newtoString = function (str) {  //与join方法类似
        var string = '';
        if (this.length == 1) {
            return string + this[this.length - 1]
        } else {
            string += this[0]
            for (var i = 1; i < this.length; i++) {
                string += (',' + this[i])
            }
            return string
        }
    }
    var str = arr.newtoString();
    console.log(str);
    console.log(arr1.newtoString());
    console.log(arr2.newtoString());

2.JavaScript Array includes() method

Definition and usage

includes()Method determines whether an array contains the specified element.

This method returns if the array contains elements, trueotherwise it returns false.

Note: includes()Methods are case-sensitive.

Parameter value

parameter describe
element Required. The element to search for.
start Optional. Default is 0. At which position in the array to start searching.

Native js handwritten implementation:

 var arr = [12, 15, 25, 36, 88]
    var arr1 = [16]
    var arr2 = ["ni", "hao", "jian", "jian"]
    Array.prototype.newIncludes=function(str,start){
        var startIndex=0;
        if(start){
            if(start<0){
                startIndex=this.length+start;
            }else{
                startIndex=start;
            }
        }
        for(var i=startIndex;i<this.length;i++){ //循环遍历数组,检索符合条件的值
            if(this[i]===str){  //进行判断是否相等
                return true
            }
        }
        return false
    }
    console.log(arr.newIncludes(25,3));
    console.log(arr.newIncludes(22));
    console.log(arr2.newIncludes('ni'));
    console.log(arr2.newIncludes('NI'));

3. JavaScript Array valueOf() method

Definition and usage

valueOf()Method returns array.

valueOf()method is the default method of array objects.

Note: valueOf()Method does not modify the original array.

parameter

No parameters.

Native js handwritten implementation:

  var arr = [12, 15, 25, 36, 88]
    var arr1 = ["ni", "hao", "jian", "jian"]
    Array.prototype.newValueOf=function(){
        //错误示例
        // var newarr=this;
        //正确示例
        var newarr=[];
        for(var i=0;i<this.length;i++){
            newarr[i]=this[i];
        }
        return newarr;
    }

    console.log(arr.newValueOf());
    console.log(arr1.newValueOf());

4. JavaScript Array unshift() method

Definition and usage

unshift()Method adds a new item to the beginning of the array and returns the new length.

Note: unshift()The method changes the length of the array.

Tip: To add a new item to the end of the array, use push()the method.

Parameter value

parameter describe
item1, item2, ..., itemX Required. The item to add to the beginning of the array.

Native js handwritten implementation:

    var arr = [12, 15, 25, 36, 88]
    var arr1 = [16]
    var arr2 = ["ni", "hao", "jian", "jian"]
    Array.prototype.newUnshift=function(){
        //记录一下长度,防止后期数组变化时不受影响
        var arrlen=this.length;
        var arglen=arguments.length;
        //创建一个临时数组去存储之前数组中的值
        var newarr=[];
        for(var i=0;i<this.length;i++){
            newarr[i]=this[i];
        }
        //将数组中的值进行从新赋值
        for(var i=0;i<arrlen+arglen;i++){
            if(i<arglen){
                this[i]=arguments[i]; //判断是否将传来的值全部插入数组前完毕
            }else{
                this[i]=newarr[i-arglen]
            }
        }
    }
    arr.newUnshift();
    console.log(arr);
    arr.newUnshift("16",14)
    console.log(arr);

5. JavaScript Array fill() method

Definition and usage

fill()Method fills the specified element in the array with a static value.

You can specify where the padding begins and ends. If not specified, all elements will be filled.

Note: fill()The original array will be overwritten.

Parameter value

parameter describe
value Required. The value used to populate the array.
start Optional. The index at which to start filling the array (default is 0).
end Optional. The index at which to stop filling the array (defaults to array.length).

Native js handwritten implementation:

    var arr = [12, 15, 25, 36, 88]
    var arr1 = [16]
    var arr2 = ["ni", "hao", "jian", "jian"]
    Array.prototype.newFill=function(val,start,end){
        var startIndex=0;
        var endIndex=this.length;
        if(start){
            startIndex=start;
        }
        if(end){
            endIndex=end;
        }
        for(var i=startIndex;i<endIndex;i++){
            this[i]=val;
        }
    }

    arr.newFill('ha',1,5)
    console.log(arr);

6. JavaScript Array concat() method

Definition and usage

concat()Method used to concatenate two or more arrays.

concat()The method does not change the existing array but returns a new array containing the values ​​of the concatenated array.

Parameter value

parameter describe
array2, array3, ..., arrayX Required. The array to be concatenated.

Native js handwritten implementation:

  var arr = [12, 15, 25, 36, 88]
    var arr1 = [16]
    var arr2 = ["ni", "hao", "jian", "jian"]
    Array.prototype.newConcat = function () {
        //创建一个临时数组去存储之前数组中的值
        var newarr = [];
        for (var i = 0; i < this.length; i++) {
            newarr[i] = this[i];
        }
        for(let i=0;i<arguments.length;i++){    //循环遍历次数等于传递的参数的个数
            var arrdeslen=newarr.length; //每次循环重新获取一下新数组的长度
            for(var j=0;j<arguments[i].length;j++){ //循环遍历次数等于获取每一个参数的数组长度 
                newarr[arrdeslen+j]=arguments[i][j]    //在新数组后面接上传递过来的参数数组
            }
        }
        return newarr;
    }
    var newarr=arr.newConcat(arr1,arr2)
    console.log(newarr);

7. JavaScript Array map() method

Definition and usage

map()Method creates a new array using the result of calling the function for each array element.

map()Method calls the provided function once for each element in the array, in sequence.

Note: map()The function is not executed on array elements that have no value.

Note: map()The original array will not be changed.

Parameter value

parameter describe
function(currentValue, index, arr) Required. Function run for each element in the array.

Function parameters:

parameter describe
currentValue Required. The value of the current element.
index Optional. The array index of the current element.
arr Optional. The array object to which the current element belongs
thisValue

Optional. The value to be passed to the function to use as its "this" value.

If this parameter is empty, the value "undefined" will be passed as its "this" value.

Native js handwritten implementation:

    var arr = [12, 15, 25, 36, 88]
    var arr2 = ["ni", "hao", "jian", "jian"]
    Array.prototype.newMap = function (fun) {
        var newarr=[];
        for(var i=0;i<this.length;i++){  //循环遍历,遍历到数组中每一个数值
           newarr[i]= fun(this[i])  //将经过函数作用过的值传递给新数组
        }
        return newarr    //将新数组返回
    }
    function test(val){ //测试函数
        return val*2
    }
    console.log(arr.newMap(test));

8. JavaScript Array filter() method

Definition and usage

filter()Method creates an array populated with all array elements that pass the test (provided as a function).

Note: filter()This function will not be executed on array elements that have no values.

Note: filter()The original array will not be changed.

Parameter value

parameter describe
function(currentValue, index, arr) Required. Function run for each element in the array.

Function parameters:

parameter describe
currentValue Required. The value of the current element.
index Optional. The array index of the current element.
arr Optional. The array object to which the current element belongs
thisValue

Optional. The value to be passed to the function to use as its "this" value.

If this parameter is empty, the value "undefined" will be passed as its "this" value.

Native js handwritten implementation:

    var arr = [12, 25, 15, 36, 88]
    var arr2 = ["ni", "hao", "jian", "jian"]
    Array.prototype.newFilter = function (fun) {
        var newarr=[];
        for(var i=0,j=0;i<this.length;i++,j++){  //循环遍历,遍历到数组中每一个数值  //新数组索引加一
          if(fun(this[i])){         //判断是否满足条件
              newarr[j]=this[i];    //满足条件的赋值给新数组               
          }
        }
        return newarr    //将新数组返回
    }
    function test(val){ //测试函数
        return val>15
    }
    console.log(arr.newFilter(test));

9. JavaScript Array forEach() method

Definition and usage

forEach()The method calls the function once for each element in the array in sequence.

Note: The method is not executed for array elements that have no value forEach().

Parameter value

parameter describe
function(currentValue, index, arr) Required. Function run for each element in the array.

Function parameters:

parameter describe
currentValue Required. The value of the current element.
index Optional. The array index of the current element.
arr Optional. The array object to which the current element belongs
thisValue

Optional. The value to be passed to the function to use as its "this" value.

If this parameter is empty, the value "undefined" will be passed as its "this" value.

Native js handwritten implementation:

    var arr = [12, 15, 25, 36, 88]
    var arr2 = ["ni", "hao", "jian", "jian"]
    Array.prototype.newForeach = function (fun) {
        for(var i=0;i<this.length;i++){  //循环遍历,遍历到数组中每一个数值
           this[i]= fun(this[i])  //将经过函数作用过的值传递给数组
        }
    }
    function test(val){ //测试函数
        return val*2
    }
    var sum=0;
    function myFunction(item) {
  sum += item;
}  
    arr.newForeach(myFunction)
    console.log(sum);
    arr.newForeach(test)//证明Foreach方法会改变原数组导致发生错误
    console.log(arr);

10. JavaScript Array reduce() method

Definition and usage

reduce()Method reduces an array to a single value.

reduce()Method executes the provided function for each value of the array (from left to right).

The return value of the function is stored in the accumulator (result/total).

Note: The method is not executed for array elements without values reduce().

注释:reduce() 方法不会改变原始数组。

参数值

参数 描述
function(total, currentValue, index, arr) 必需。为数组中的每个元素运行的函数。

函数参数:

参数 描述
total 必需。initialValue,或函数先前返回的值。
currentValue 必需。当前元素的值。
index 可选。当前元素的数组索引。
arr 可选。当前元素所属的数组对象
initialValue 可选。作为初始值传递给函数的值。

原生js手写实现:

    var arr = [12.5, 15.6, 25, 36, 88]
    var arr1 = [16]
    var arr2 = ["ni", "hao", "jian", "jian"]
    Array.prototype.newReduce = function (fun) {
        var first = this[0];
        for (var i = 1; i < this.length; i++) {
            var first=fun(first, this[i])
        }
        return first
    }
    function myFunc(total, num) {
        return total - num;
    }
    function getSum(total, num) {
  return total + Math.round(num);
}

   console.log( arr.newReduce(myFunc));
   console.log(arr.newReduce(getSum));

十一.JavaScript Array reduceRight() 方法

定义和用法

reduceRight() 方法将数组缩减为单个值。

reduceRight() 方法为数组的每个值(从右到左)执行提供的函数。

函数的返回值存储在累加器中(结果/总计)。

注释:对没有值的数组元素,不执行 reduceRight() 方法。

参数值

参数 描述
function(total, currentValue, index, arr) 必需。为数组中的每个元素运行的函数。

函数参数:

参数 描述
total 必需。initialValue,或函数先前返回的值。
currentValue 必需。当前元素的值。
index 可选。当前元素的数组索引。
arr 可选。当前元素所属的数组对象
initialValue 可选。作为初始值传递给函数的值。

原生js手写实现:

    var arr = [12, 156, 25, 36, 88]
    var arr1 = [16]
    var arr2 = ["ni", "hao", "jian", "jian"]
    Array.prototype.newReduceRight = function (fun) {
        var first = this[this.length-1];
        for (var i = 0; i < this.length-1; i++) {
            var first = fun(first, this[i])
        }
        return first
    }
    function myFunc(total, num) {
        return total - num;
    }
    console.log(arr.newReduceRight(myFunc));

十二.JavaScript Array indexOf() 方法

定义和用法

indexOf() 方法在数组中搜索指定项目,并返回其位置。

搜索将从指定位置开始,如果未指定开始位置,则从头开始,并在数组末尾结束搜索。

如果未找到该项目,则 indexOf() 返回 -1。

如果该项目出现多次,则 indexOf() 方法返回第一次出现的位置。

注释:第一项的位置为 0,第二项的位置为 1,依此类推。

提示:如果您想从尾到头搜索,请使用 lastIndexOf() 方法。

参数值

参数 描述
item 必需。要搜索的项目。
start 可选。从哪里开始搜索。负值给定的位置将从结尾计数,然后搜索到最后。

原生js手写实现:

        var arr = [12, 15, 25, 36, 88]
    var arr1 = [16]
    var arr2 = ["ni", "hao", "jian", "jian"]
    Array.prototype.newIndexOf=function(item,start){
        var startIndex=0;
        if(start){
            if(start<0){
                startIndex=this.length+start;
            }else{
                startIndex=start;
            }
        }
        for(var i=startIndex;i<this.length;i++){
            if(item===this[i]){
                return i;
            }
        }
        return -1;
    }
   console.log( arr.newIndexOf(36,4));
   console.log( arr2.newIndexOf('jian'));
   console.log( arr2.newIndexOf('jian',3));

十三.JavaScript Array lastIndexOf() 方法

定义和用法

lastIndexOf() 方法在数组中搜索指定项目,并返回其位置。

搜索将从指定位置开始,如果未指定开始位置,则从末尾开始,并在数组的开头结束搜索。

如果未找到该项目,则 lastIndexOf() 方法返回 -1。

如果要搜索的项目不止一次出现,lastIndexOf() 方法将返回最后一次出现的位置。

提示:如果要从头到尾搜索,使用 indexOf() 方法。

参数值

参数 描述
item 必需。要搜索的项目。
start 可选。从哪里开始搜索。负值的给定的位置从末尾计数,然后搜索到开头。

原生js手写实现:

        var arr = [12, 15, 25, 36, 88]
    var arr1 = [16]
    var arr2 = ["ni", "hao", "jian", "jian"]
    Array.prototype.newLastIndexOf=function(item,start){
        var startIndex=this.length-1;
        if(start){
            if(start<0){
                startIndex=this.length+start;
            }else{
                startIndex=start;
            }
        }
        for(var i=startIndex;i>=0;i--){
            if(item===this[i]){
                var ls=i
            }
        }
        if(ls){
            return ls;
        }else{
            return -1;
        }
    }
     
   console.log( arr.newLastIndexOf(36,4));
   console.log( arr2.newLastIndexOf('jian'));
   console.log( arr2.newLastIndexOf('jian',-3));

十四.JavaScript Array isArray() 方法

定义和用法

isArray() 方法确定对象是否为数组。

如果对象是数组,则此函数返回 true,否则返回 false。

参数值

参数 描述
obj 必需。需测试的对象。

原生js手写实现:

    var arr = [12, 15, 25, 36, 88]
    var arr1 = []
    var arr2 = ["ni", "hao", "jian", "jian"]
    Array.prototype.newIsArray = function () {
        if(this.constructor.name=="Array"){
            return true;
        }else{
            return false
        }
    }
    console.log(arr.newIsArray());

十五.JavaScript Array splice() 方法

定义和用法

splice() 方法向/从数组添加/删除项目,并返回删除的项目。

注释:splice() 方法会改变原始数组。

参数值

参数 描述
index 必需。整数,指定在什么位置添加/删除项目,使用负值指定从数组末尾开始的位置。
howmany 可选。要删除的项目数。如果设置为 0,则不会删除任何项目。
item1, ..., itemX 可选。要添加到数组中的新项目。

原生js手写实现:

   var arr = [12, 15, 25, 36, 88]
    var arr2 = ["ni", "hao", "jian", "jian"]
    Array.prototype.newSplice = function (index, howmany) {
        //确定好删除位置索引的值
        if (index < 0) {
            var startindex = this.length + index;
        } else {
            startindex = index;
        }
        //调节一下删除的数量
        if (howmany > 0) {
            var number = howmany;
        } else {
            number = 0
        }
        //创建一个临时数组,将删除索引之后的值存起来
        var arrlen = this.length;
        var newarr = [];
        for (var i = startindex; i < arrlen; i++) {
            newarr[i - startindex] = this[i]
        }
        //先将传递过来的需要插入的数据长度查出来
        var arglen = arguments.length - 2;
        for (var i = 0; i < arglen; i++) {  //将传来的数据插入到数组当中去
            this[i + startindex] = arguments[i + 2]
        }
        //将数组中剩余的插入到数组中去       
        for (var i = number; i < newarr.length; i++) {
            this[startindex + arglen + i - number] = newarr[i];
        }
    }
    arr.newSplice(2, 0, 56, 55)
    var fruits = ["Banana", "Orange", "Apple", "Mango"];
    fruits.newSplice(2, "Lemon", "Kiwi");
    console.log(fruits);
    console.log(arr);

十六.JavaScript Array copyWithin() 方法

定义和用法

copyWithin() 方法将数组元素复制到数组中的另一个位置,覆盖现有值。

copyWithin() 方法永远不会向数组添加更多项。

提示:copyWithin() 方法会覆盖原始数组。

参数值

参数 描述
target 必需。将元素复制到的索引位置。
start 可选。开始复制元素的索引位置(默认为 0)。
end 可选。停止从中复制元素的索引位置(默认为 array.length)。

原生js手写实现:

    var arr = [12, 15, 25, 36, 88]
    var arr1 = [16]
    var arr2 = ["ni", "hao", "jian", "jian"]
    Array.prototype.newCopyWithin = function (target,start,end) {
        var startIndex=0;
        var endIndex=this.length;
         //开始索引,负数从后数
        if(start){
            if(start<0){
                startIndex=this.length+start;
            }else{
                startIndex=start;
            }
        }
            //结束索引,负数从后数
        if(end){
            if(end<0){
                endIndex=this.length+end;
            }else{
                endIndex=end;
            }
        }
        //创建一个临时数组,将原始值存放起来
        var newarr=[];
        for(var i=0;i<this.length;i++){
            newarr[i]=this[i];
        }
        //进行复制
        for(var i=target,j=startIndex;i<this.length&&j<endIndex;i++,j++){
            this[i]=newarr[j];
        }
    }

arr.newCopyWithin(2,0)
console.log(arr);
arr2.newCopyWithin(2,0,1)
console.log(arr2);

Guess you like

Origin blog.csdn.net/m0_55315930/article/details/127901940