Home >Web Front-end >Front-end Q&A >There are several ways to assign values ​​to arrays in JavaScript

There are several ways to assign values ​​to arrays in JavaScript

青灯夜游
青灯夜游Original
2022-02-16 17:32:3814193browse

There are three ways to assign values ​​to arrays: 1. After creating the array, use the form "array name [subscript] = value;" to assign values ​​one by one; 2. Use "var array name = new Array (value list );" statement assigns values ​​while creating the array; 3. Use the "var array name = [value list];" statement to assign values ​​while creating the array.

There are several ways to assign values ​​to arrays in JavaScript

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

JavaScript array assignment method

Method 1:

First create an empty array:

var arr = new Array(); //空数组
var arr = new Array(2); //当给Array()函数出入一个参数时,可指定数组长度(可以不指定,js的数组是变长的,会随着加入的元素改变数组的长度)
var arr = []; //空数组

Assign a value to an empty array

arr[0] = 1;
arr[1] = 2;

There are several ways to assign values ​​to arrays in JavaScript

Method 2:

Assign a value while creating an array

var arr = new Array(2,3);

There are several ways to assign values ​​to arrays in JavaScript

Method 3:

Create an array and assign values ​​at the same time

var arr = [3,4];   //直接输入一个数组,也叫字面量数组

There are several ways to assign values ​​to arrays in JavaScript

【 Related recommendations: javascript learning tutorial

The above is the detailed content of There are several ways to assign values ​​to arrays in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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