“This is the 11th day of my participation in the Gwen Challenge in November. See details: The Last Gwen Challenge in 2021.”


preface

In the actual project, I believe that the most used native API should be arrays and objects, but for their official API, it seems that we have little real understanding, so today I will combine my own knowledge, share my understanding of arrays

An array of API

What do you know about the array API? (I don’t think this is a problem, just look it up on the Internet)

Put the MDN portal here

Slice, splice, indexOf, unshift, Shift, POP, push, sort, reverse, concat, Join

But most of the questions on the web about array apis are, what apis change the array itself, and what apis don’t change the array itself, and those are all pretty much generic stuff, so TODAY I want to talk about something a little bit more bizarre

Push methods on arrays

Push method has universality. This method, when used with call() and apply(), can be applied to array-like objects. Typically, push adds data at the end of the array, enqueueing and pushing

But have you ever wondered how array push actually adds data?

A little question

But can push really only add data to the end of an array? Let’s look at an example

var obj = {
  "2": "a",
  "3": "b",
  "length": 2,
  "push": Array.prototype.push
}
obj.push("c");
obj.push("d");
Copy the code

After two pushes, what is obj going to be? Think about it for a moment, and the answer will come

var obj = {
  "2": "c",
  "3": "d",
  "length": 4,
  "push": Array.prototype.push
}
Copy the code

Anything was so amazing!!

The implementation principle of push

The push method uses the length attribute to decide where to start inserting a given value. If length cannot be converted to a numeric value, the index of the inserted element is 0. But when length does not exist, it will be created

The only array-like objects of the native class are Strings, although they are not suitable for this method because Strings are immutable.

The value of the object’s length attribute is used to determine the position of the insert.

Array.prototype.push = function (target) {
    obj[obj.length] = target;
    obj["length"]++;
}
Copy the code

MDN explanation of array. push

conclusion

As mentioned above, few students should pay attention to how push mode is implemented. I don’t think we should be led astray by the public, which is all over the web talking about apis that modify the array itself, focusing on this issue. I think to solve a problem should be to understand the essence of the problem, from the problem itself, the future encounter similar can be easily solved