Home  >  Article  >  Web Front-end  >  What are the ways to define javascript arrays?

What are the ways to define javascript arrays?

青灯夜游
青灯夜游Original
2021-04-19 19:01:5211986browse

How to define an array: 1. Use the "var arr=[value 1, value 2, value 3..];" statement to define; 2. Use "var arr=new Array(value 1, value 2. Value 3..);" statement to define; 3. Use "var array=new Array(size)" statement to define.

What are the ways to define javascript arrays?

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

What is an array

An array is a collection of data

Its expression is a continuous memory address in the memory

The array name is actually the first address of the continuous memory address

About the characteristics of arrays in js

There is no need to specify the data type when defining an array

Array There is no need to specify the array length when defining

Arrays can store data of any data type (for example, one element stores integer type and one element stores string type. This is possible in JS)

Syntax for defining arrays:

var arr=[值1,值2,值3];                     //隐式创建
var arr=new Array(值1,值2,值3);      //直接实例化
var array=new Array(size);           //创建数组并指定长度

Example:

//方法一
var arr1 = [1,3,5,7,9];
document.write(arr1[2] + &#39;<br>&#39;);
 
//方法二
var arr2 = new Array(2,4,6,8,10);
document.write(arr2[3] + &#39;<br>&#39;);
 
//方法三
var arr3 = new Array(3);//固定数组长度为3
arr3[0] = 1;
arr3[1] = 2;
arr3[2] = 3;
document.write(arr3[2] + &#39;<br>&#39;);

Meaning of symbols in JS:

() Indicates function execution

[]Indicates syntax simulation, indicating simulated instances of the Array class (=new Array())

{}Indicates syntax simulation, which means simulating instances of the Object class (=new Object())

//Indicates syntax simulation (regular objects), which means simulating instances of the RegExp class (=new RegExp ())

About array length

Array object.length

In js, every array object can Call the length attribute, which indicates how many array elements there are under the array object

Example:

var row = [&#39;zhangsan&#39;,&#39;lisi&#39;,&#39;wangwu&#39;];
doucument.write(&#39;共有&#39;+row.length+&#39;个人<br>&#39;);

var length = row.length;//对数组进行遍历
for (var i=0;i<length;i++){
doucument.write(row[i]+&#39;<br>&#39;);
}

[Recommended learning: javascript advanced tutorial]

The above is the detailed content of What are the ways to define javascript arrays?. 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