Home > Web Front-end > Front-end Q&A > What are the ways to define arrays in javascript

What are the ways to define arrays in javascript

青灯夜游
Release: 2021-10-15 15:36:17
Original
10161 people have browsed it

How to define an array in JavaScript: 1. Use the "var array name = [value list]" statement; 2. Use the "var array name = new Array (value list)" statement; 3. Use "var Array name = new Array (array length value); array name [subscript] = value;" statement.

What are the ways to define arrays in javascript

The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.

Use array literals to define

The syntax format of array literals: multiple value lists in square brackets, Separate with commas.

var 数组名=[值列表]
Copy after login

The value list can be empty, then an empty array will be created.

Example:

var a = [];  //空数组
var a = [1, true, "0", [1,0], {x:1,y:0}];  //包含具体元素的数组
Copy after login

Use the constructor method to define

Use the new operator to call Array() type function can construct a new array.

var 数组名 = new Array();  //空数组
var 数组名 = new Array(值列表);  //实数组
Copy after login

If you pass a numeric parameter to Array(), the parameter value is equal to the attribute value of the array length, which can define the length of the array, that is, the number of elements it contains.

var a = new Array(5);  //指定长度的数组
Copy after login

At this time, the default value of each element is undefined, which can be initialized by assigning a value to each element:

a[0] = 1;
a[1] = 2;
a[2] = 3;
Copy after login

[Recommended learning: javascript Advanced Tutorial

The above is the detailed content of What are the ways to define arrays in javascript. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template