Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Array.apply(), new Array(), arr," the difference between the three


Jun 01, 2021 Article blog


Table of contents


Why would you write this article? L ooking at the Vue document 渲染函数 when you find a problem curious, Array.apply(null, { length: 20 }) Why define arrays like this? Then look up the data to make a small knot record, sparrows are small, dirty all.

 Array.apply(), new Array(), arr," the difference between the three1

Array.apply()

Apply() is explained in MDN as follows:

func.apply(thisArg, [argsArray])

ThisArg is a must. T he value of this used when the func function runs. Note that this may not be the actual value that the method sees: if the function is in non-strict mode, it is automatically replaced with a global object when specified as null or undefined, and the original value is wrapped.

argsArray optional. A n array or class array object in which array elements are passed to the func function as separate arguments. I f the value of the argument is null or undefined, no arguments need to be passed in. Class array objects can be used from ECMAScript 5

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

 Array.apply(), new Array(), arr," the difference between the three2

From this, it can be seen that {length:20} class array such as argument only the property of length which is equivalent to creating an array of 20 lengths, each element undefined 类数组

(20) [undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined]

 Array.apply(), new Array(), arr," the difference between the three3

new Array()

new Array(20) and Array(20) simply create an array of 20 lengths and the elements are empty

(20) [empty × 20]

arr = []

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

From this you can see new Array(20) and let arr=[];arr.length= 20

Array.from()

The Array.from() method creates a new, shallow-copy array instance from an array-like or iterative object.

Array.from({length:20})
(20) [undefined, undefined, undefined, undefined, undefined, undefined, undefi

Source: Public Number - Clown's Cabin Author: Clown

The above is a description of the difference W3Cschool编程狮 and Array.apply(), new Array(), arr., and I hope to help you.