Home > Web Front-end > JS Tutorial > How to define array in js

How to define array in js

下次还敢
Release: 2024-05-07 22:09:17
Original
1005 people have browsed it

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 array in js

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>
Copy after login

Array literal

You can also use a more concise array literal syntax:

<code class="js">const myArray = [1, 2, 3];</code>
Copy after login

Keywordnew Definition

You can also usenew keywords and Array constructors to define arrays:

<code class="js">const myArray = new Array(3); // 创建一个包含 3 个 undefined 元素的数组</code>
Copy after login

Other methods

There are some other methods that can be defined Arrays, but they are less commonly used:

  • Array.of() Method: Creates a new array containing the specified elements.
  • Create from existing array: A new array can be created from an existing array by copying or using the slice() method.
  • Expand operator: Expand an iterable object (such as an array or collection) into an array by using the spread operator (...).

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template