Mapping Array in Javascript with sequential numbers

后端 未结 4 1868
逝去的感伤
逝去的感伤 2021-02-04 17:40

The following code:

let myArray = Array.apply(null, {length: 10}).map(Number.call, Number);

Creates the following Array:

[0, 1,         


        
4条回答
  •  北恋
    北恋 (楼主)
    2021-02-04 18:26

    Array.apply(null, {length: 10}) 
    

    //> it outputs the array of undefined, with the length of ten, why: it takes null for execution because it does not need this for execution, besides this argument must be tepeof object, and as we know: typeof null === 'object', if you will place any other object instead of null, it will do the same thing, it matters only what is the length of the second argument( it tests the length of the second argument),

    .map(Number.call, Number);

    decompose(we know that Number constructor is Function.prototype(Number.proto), so):

    .map(function(){
    Function.prototype.call.apply(this, arguments)
    }, Number)// the second arg is the this value that map function takes during each iteration
    

    We also know that this is Number, cause every time it calls Number as this:

    Function.prototype.call.apply(Number, arguments)
    

    });//here we don't need second argument

    Now we compose everything again: Function.prototype => Number,

    call.apply(Number, arguments); => call(arguments[0], arguments[1])
    

    reason: arguments is array-like object, we can still pass it to apply method, but we cannot to call, cause it takes arguments separated by comma.You cannot define arguments as an argument, so you need to indicate what it is looking for: index, and that is arguments[1], as this value it must take any object, so it take: null, or anything, but it must be present:

    return Number.call(null, arguments[1]);
    

    Here Number is an identity function:

    function example(x){
     return x;
    }
    

    so Number(e) == example(e); so on first iteration:

    Number(0) //it takes 0 index:
    
    return 0..
    

    then:

    Number(1)//cause it takes the index of the second element:
    
    return 1..
    

    Thanks for reading...

提交回复
热议问题