Using the slice () method for an array of type Object

I got confused with the exit.

var arrLike = {0:'Martin', 1:78, 2:67, 3:['L', 'M', 'P'], length: 4};

If I use slice()on arrLike:

var newArr = Array.prototype.slice.call(arrLike, 0);

Output:

console.log(newArr);
["Martin", 78, 67, Array[3]]

How does this happen? I cannot complete my work using output.

+4
source share
2 answers

Foreword: Note that Array[3]on your console output, this is how the console displays it to you. Your newArrreally:

["Martin", 78, 67, ['L', 'M', 'P']]

This is because it is defined as slice. In short:

  • Creates a new empty array
  • Reads the property lengthof what you give it
  • Passes from start index (default 0) to end index (default length - 1); call loop variablek
    • , , k k - start.
  • length k - start.

( ):

function slice(start, end) {
    var n, k, result;
    start = arguments.length < 1 ? 0 : +start;
    end = arguments.length < 2 ? +this.length : +end;
    result = [];
    for (var k = start, n = 0; k < end; ++k, ++n) {
        if (n in this) {
            result[n] = this[k];
        }
    }
    result.length = n;
    return result;
}

gory.

arrLike length 0, 1, 2 3, , .

+7

slice(). slice() end, , this.length ...

  1. end undefined, relativeEnd len; relativeEnd ToInteger ().

, 4 arrLike .

...

var arrLike = {0:'Martin', 1:78, 2:67, 3:['L', 'M', 'P'], length: 6, 4: 'test'};

+1

Source: https://habr.com/ru/post/1624326/


All Articles