Get the App
SLTechnology News&Howtos  ›  Development  › 

What's the difference between Array.apply (), new Array () and arr = []

Shulou Source: shulou.com Published: 2022-06-01 11:34:12 10月03日 Update

This article editor for everyone to introduce in detail "Array.apply (), new Array () and arr = [] what's the difference", the content is detailed, the steps are clear, the details are handled properly, I hope this "Array.apply (), new Array () and arr = [] what's the difference" article can help you solve your doubts, the following follows the editor's train of thought slowly in depth, together to learn new knowledge.

Array.apply ()

Apply () is explained in MDN as follows:

Func.apply (thisArg, [argsArray])

ThisArg must be selected. The this value used when the func function is running. Note that this may not be the actual value seen by this method: if this function is in non-strict mode, it is automatically replaced by pointing to the global object when specified as null or undefined, and the original value is wrapped.

ArgsArray is optional. An array or class array object in which the array elements are passed to the func function as separate arguments. If the value of the parameter is null or undefined, no parameter needs to be passed in. Since ECMAScript 5, you can use class array objects.

Function printArguments () {console.log (arguments) Array.prototype.forEach.call (arguments, function (item) {console.log (item);});} printArguments (undefined,undefined)

Thus it can be seen that {length:20} is an array of classes, for example, argument only provides the attribute of length, which is equivalent to creating an array of length 20, each element is undefined.

(20) [undefined, undefined] new Array ()

New Array (20) and Array (20) simply create an array of length 20 and empty elements

(20) [empty x 20] arr= [] let arr= []; arr.length= 20 (20) [empty x 20]

Thus it can be seen that new Array (20) is equivalent to let arr= []; arr.length= 20

Array.from ()

The Array.from () method creates a new, shallow copy of the array instance from a similar array or iterable object.

Array.from ({length:20}) (20) [undefined, undefi read here, this article "what's the difference between Array.apply (), new Array () and arr = []" has been introduced. If you want to master the knowledge points of this article, you still need to practice and use it yourself to understand it. If you want to know more about related articles, welcome to follow the industry information channel.

Tags: Array object element function parameter article content method thus length primitive proper global just instance actual attribute idea copy Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Docker Xiaomi OPPO Reno Redmi Microsoft