To define a JavaScript array, you can use the following methods: Square brackets ([]) enclose element array literal syntax [1, 2, 3] new Array(3) constructor Array.of() method from Existing array creation spread operator (...)
How to define an array in JavaScript
Direct definition
The most direct way is to use square brackets ([]
) to enclose elements:
<code class="js">const myArray = ['apple', 'banana', 'orange'];</code>
Array literal
You can also use a more concise array literal syntax:
<code class="js">const myArray = [1, 2, 3];</code>
Keywordnew
Definition
You can also usenew
keywords and Array
constructors to define arrays:
<code class="js">const myArray = new Array(3); // 创建一个包含 3 个 undefined 元素的数组</code>
Other methods
There are some other methods that can be defined Arrays, but they are less commonly used:
slice()
method. ...
). The above is the detailed content of How to define array in js. For more information, please follow other related articles on the PHP Chinese website!