Home > Article > Web Front-end > There are several ways to assign values to arrays in JavaScript
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.
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;
Method 2:
Assign a value while creating an array
var arr = new Array(2,3);
Method 3:
Create an array and assign values at the same time
var arr = [3,4]; //直接输入一个数组,也叫字面量数组
【 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!