In the previous article, we learned how to use includes() to determine whether an array contains a specified value. Please see "How to use includes() in js to determine whether an array contains a specified value". This time we will take a look at how to create an array with a variable number. You can refer to it if you need it.
Do you still remember that the editor introduced How to create an array object? If you don’t remember or don’t know, you can click on the text to view it.
Previously we introduced how to create an array object through array. Today we are going to create a variable-length array, so we can no longer use array to create it. So what do we need to use to create it?
First let’s look at a small example.
var arr = new Array(7); arr[0] = "one"; arr[1] = "two"; arr[2] = "three"; arr[3] = "one"; arr[4] = "two"; console.log(arr);
This is the array object created through array before. The result is
Let’s take a look at the array created through array.of.
var nums=new Array.of(7); console.log(nums);
The result of this is
You can see the difference right now.
Although they are both 7, the 7 in array represents the length of the array, while the 7 in Array.of represents creating an array with a single element 7.
Having said so much, let us take a look at this method in detail.
The Array.of() method creates a new array instance with a variable number of arguments, regardless of the number or type of arguments. The difference between Array.of() and Array constructors is the handling of integer arguments: Array.of(7) creates an array with a single element 7 , while Array(7) creates an empty array of length 7 (note: this refers to an array with 7 empty positions (empty), not an array composed of 7 undefined).
Let’s take a look at the syntax format of this method.
Array.of(任意个参数)
The parameters of this method can be any number, and these parameters will become the elements in the returned array in order.
That’s all. If you need it, you can read: javascript advanced tutorial
The above is the detailed content of How to create an array with variable number in js. For more information, please follow other related articles on the PHP Chinese website!