Home > Computer Tutorials > Computer Knowledge > How to declare an array in JavaScript

How to declare an array in JavaScript

WBOY
Release: 2024-01-22 11:45:13
forward
582 people have browsed it

How to declare an array in JavaScript

How to declare an array in javascript

The most common way is this:

var arr = [];arr is the variable name, you can choose it as you like (as long as it meets the naming convention)

The above indicates that a new array is created.

There are two types of array assignment, one is assignment when creating, and the other is assignment after creation, as follows

Assign value when creating:

var arr = ['HTML5 Academy', 2];

// An array is created. The array has two elements. The first is the string HTML5 School, and the second is the number 2. After creation, assign a value:

var arr = [];

arr[0] = 'HTML5 Academy';

arr[1] = 2;

// Create an empty array, assign the value of the first array element to HTML5 School, and assign the value of the second array element to 2. In addition to this most common method of creating an array, there is also this (not commonly used) , nor recommended for use in practice):

var arr = new Array();

var arr2 = new Array('HTML5 Academy', 2);

How to define an array in javascript

There are two main ways to define functions:

1. Constructor method:

2. Dynamically add as many values ​​as you like:

var myArray1 = new Array();

myArray1[0] = 1;

myArray1[1] = 2;

myArray1[2] = 3;

...3. Use an integer argument to control the capacity of the array (number of elements):

var myArray2 = new Array(2);

//When new, the number of elements in the array is given, but it should be noted that the capacity of the array can be changed at any time when assigning values ​​to elements later

myArray2[0] = 1;

myArray2[1] = 2;

myArray2[2] = 3;

console.log(myArray2.length);//34. Assign a value to the array when defining:

var myArray3 = new Array("1","2","4","5");

// You can also reassign the array elements later:

myArray3[1] = "hello word";

console.log(myArray3[1]); //Return hello word instead of 22. Defined in literal way:

var myArray4 = [1,2,3,4,5];

The above is the detailed content of How to declare an array in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

source:docexcel.net
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template