Home Web Front-end JS Tutorial Mixed use of js one-dimensional arrays, multi-dimensional arrays and objects_javascript skills

Mixed use of js one-dimensional arrays, multi-dimensional arrays and objects_javascript skills

May 16, 2016 pm 03:06 PM
one-dimensional array Multidimensional Arrays

The main purpose of this article is to explain the mixed use of JavaScript arrays and objects. Due to the weak checking characteristics of JS, different types of variables can be stored in JS arrays at the same time. For example, you can store numbers, strings, characters, Objects and other contents are placed in the same array. Objects can also do the same thing. The difference is that objects can specify aliases for each member in the object, so that the data is more readable during programming, such as:

var arr1 = ["飞鱼", 25, 172, "江苏"];
var person = {name:"飞鱼",age: 25, height:172,province: "江苏"};
Copy after login

In this way, is person.name easier to read and use than arr1[0]? Of course, arrays and objects each have their own advantages. The focus of this article is to combine the advantages of both and use them comprehensively.

One-dimensional array
The following code creates an array named cars: first create the array, and then assign values ​​one by one

var cars=new Array();
cars[0]="Audi";
cars[1]="BMW";
cars[2]="Volvo";
Copy after login

or (condensed array): assign value when creating array object

Copy code The code is as follows:

var cars=new Array("Audi","BMW","Volvo");

Or (literal array): Do not create variables, directly assist, but pay attention to the parentheses "( )" used when creating objects, and the square brackets "[ ]" used when assigning values ​​directly. This can easily lead to errors if you are not careful.
Example
Copy code The code is as follows:

var cars=["Audi","BMW","Volvo"];

The above are three ways to create a one-dimensional array. Due to the weak checking nature of JS, you can put variables of different types in a one-dimensional array.

Two-dimensional and multi-dimensional arrays:
1. Method 1 of creating a two-dimensional array: First create a one-dimensional array, and then create one-dimensional data for all members of the one-dimensional array

var persons = new Array();

persons[0] = new Array();
persons[1] = new Array();
persons[2] = new Array();

persons[0][0] = "zhangsan";
persons[0][1] = 25;
persons[1][0] = "lisi";
persons[1][1] = 22;
persons[2][0] = "wangwu";
persons[2][1] = 32;
persons[0] = ["zhangsan", 25];
persons[1] = ["lisi", 21];
persons[2] = ["wangwu", 32];
Copy after login

Compared with the previous method, this one is much simpler and easier to read.

Copy code The code is as follows:

persons.length = 3

​ ​ 2. Method 2 of creating a two-dimensional array: First create a one-dimensional array, and then directly assign values ​​to all members of the one-dimensional array
Copy code The code is as follows:

var persons = new Array();

3. Method 3 of creating a two-dimensional array: direct assignment
Copy code The code is as follows:

var persons = [["zhangsan", 25], ["lisi", 21], ["wangwu", 32]];

4. Summary
Although the first and second methods are more troublesome, you can first create an empty multi-dimensional array and then assign values ​​according to your own needs in the for loop. The third method is relatively simple and easy to use for enumerated data.
The last question about two-dimensional arrays is what is the length of a two-dimensional or multi-dimensional array? Let’s test the following code:

Copy code The code is as follows:

document.write("persons = " + persons + "
persons.length = " + persons.length);

The output result is:
           persons = zhangsan,25,lisi,21,wangwu,32
In other words, the length property of a multi-dimensional array returns the length of the first dimension of the multi-dimensional array, not the number of elements in the multi-dimensional array.

5. How to return the number of elements of a multi-dimensional array

The following array:

Copy code The code is as follows:

var persons = [["zhangsan", 25], ["lisi", 21], ["wangwu", 32]];

通过维数(此处是3)乘以每维元素的个数(此处是2)就可以得出该多维数组的元素个数是6了。但是这并不是保险的做法,因为多维数组中每一个维度的元素个数是可以不一样的,如:

复制代码 代码如下:

var persons = [["zhangsan", 25], ["lisi", 21, 172], ["wangwu", 32]];

该数组的第一维的第二个元素数组包含三个元素,其他的只有两个,这再使用length来计算还是3,因为第一维的元素个数没变嘛。但是再使用上面的方法计算该多维数组的元素个数就不对了。
因此多维数组的length属性和一维数组一样,永远返回第一维数组的元素个数。计算多维数组的元素个数,可以自己创建一个或多个嵌套for循环来计算,如:
在知道数组的维度的情况下,可以针对该数组写算法,如二维数组:

var persons = [["zhangsan", 25], ["lisi", 21], ["wangwu", 32]];
function getArr2ElementNum(arr) {
var eleNum = 0;
if (arr == null) {
return 0;
}
for (var i = 0; i < arr.length; i++) {
for (var j = 0; j < arr[i].length; j++) {
eleNum++;
}
}
return eleNum;
}
alert(getArr2ElementNum(persons));
Copy after login


在多维数组维度过多,嵌套复杂时,通过上面的方法来写针对的算法就太累了,特别是当这个复杂的多维数组还可能随时变换维度的情况下。如下这个复杂的多重嵌套的多维数组:
var arrN = [["zhangsan", 25, [1, "wangyuchu", 54, [123, 34, 16]], 43], ["lisi", 21, 172], ["wangwu", 32, "suzhou"]];
甚至,有些多维嵌套数组比这个还复杂,那怎么计算数组元素个数呢,我写了一个求数组元素个数的函数,不管是一维还多维,也不管是多么复杂的嵌套多维数组,都可以计算出来,算法不麻烦,主要用到了递归的理念:
//判断某个对象是不是数组

function isArray(obj) {
return obj && ( typeof obj === 'object') && (obj.constructor == Array);
}

//eleNum变量初始值为0,用来统计数组元素个数
var eleNum = 0;

//递归计算某个数组元素是不是下一维数组,如果是,则继续递归下去;如果不是,统计元素个数。
function recursion(obj) {
if (isArray(obj)) {
for (var j = 0; j < obj.length; j++) {
if (!isArray(obj[j])) {
eleNum++;
continue;
}
recursion(obj[j]);
}
} else {
eleNum++;
}
}

//arr为要计算数组元素个数的一维或多维数组,通过调用递归函数recursion返回数组元素个数
function getArrNElementNum(arr) {
if (arr == null) {
return 0;
}

recursion(arr);

return eleNum;
}

//随意定义一个复杂的多维嵌套数组
var arrN = [["zhangsan", 25, [1, "wangyuchu", 54, [123, 34, 16]], 43], ["lisi", 21, 172], ["wangwu", 32, "suzhou"]];
//打印出来数组元素个数
alert(getArrNElementNum(arrN));
Copy after login

对象:
对象由花括号分隔。在括号内部,对象的属性以名称和值对的形式 (name : value) 来定义。属性由逗号分隔:

复制代码 代码如下:

var person={firstname:"Bill", lastname:"Gates", id:5566};

上面例子中的对象 (person) 有三个属性:firstname、lastname 以及 id。
空格和折行无关紧要。声明可横跨多行:

var person={
firstname : "Bill",
lastname : "Gates",
id    : 5566
};
Copy after login

对象属性有两种寻址方式:
实例

name=person.lastname;
name=person["lastname"];
Copy after login

对象和多维数组的混合使用:
         想象这么一个场景,要枚举并统计清华大学(qinghua)、北京大学(beida)、浙江大学(zheda)三所大学一共有多少个系,怎么做?
         首先,建立一个数组,数组中包括着三所学校:

复制代码 代码如下:

var departments = [qinghua, beida, zheda];

        每个学校又有很多不同或相同的学院(xx),如何表示?在这里就要用到数组包含对象了:
复制代码 代码如下:

var departments = [qinghua{xx1, xx2, xx3}, beida{xx4, xx5,
 xx6, xx7}, zheda{xx8, xx9}];

每个学院又有不同的系(d),如何表示?
复制代码 代码如下:

var departments = [qinghua{xx1:[d1, d2], xx2[d3, d5],
 xx3:[d7, d8]}, beida{xx4, xx5, xx6, xx7}, zheda{xx8,
 xx9}];
 //只是举个例子,后面两个大学我就不表示了

上述例子就是一个数组,该数组的元素是学校对象,学校对象有N个学院属性,而每个学院属性又是一个包含多个系的数组,这就是一个典型的多维数组和对象混合使用的例子,可以简单明了的说明和列表学校、学院和系之间的级别、归属和数量关系。
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Dimensional journey of PHP multi-dimensional array sorting: from one dimension to multi-dimensional Dimensional journey of PHP multi-dimensional array sorting: from one dimension to multi-dimensional Apr 29, 2024 pm 09:09 PM

One-dimensional arrays are sorted using the sort() function, two-dimensional arrays are sorted by internal elements using the usort() function, and high-dimensional arrays are sorted by hierarchical elements using the multi-layer nested usort() function. Solving the decomposition problem layer by layer is the key.

How to combine multiple arrays into one multidimensional array in PHP How to combine multiple arrays into one multidimensional array in PHP Jul 09, 2023 pm 01:08 PM

How to merge multiple arrays into a multi-dimensional array in PHP In PHP development, we often encounter the need to merge multiple arrays into a multi-dimensional array. This operation is very useful when operating large data collections and can help us better organize and process data. This article will introduce you to several common methods to achieve this operation, and attach code examples for reference. Method 1: Use the array_merge function. The array_merge function is a commonly used array merging function in PHP. It can merge multiple arrays.

How to convert a two-dimensional php array into a one-dimensional array How to convert a two-dimensional php array into a one-dimensional array Aug 03, 2023 am 11:14 AM

How to convert a php array from two dimensions to a one-dimensional array: 1. Use loop traversal to traverse the two-dimensional array and add each element to the one-dimensional array; 2. Use the "array_merge" function to merge multiple arrays into An array. Pass the two-dimensional array as a parameter to the "array_merge" function to convert it into a one-dimensional array; 3. Using the "array_reduce" function, you can process all the values ​​in the array through a callback function and finally return a result.

Python program to multiply two matrices using multidimensional arrays Python program to multiply two matrices using multidimensional arrays Sep 11, 2023 pm 05:09 PM

A matrix is ​​a set of numbers arranged in rows and columns. A matrix with m rows and n columns is called an mXn matrix, and m and n are called its dimensions. A matrix is ​​a two-dimensional array created in Python using lists or NumPy arrays. In general, matrix multiplication can be done by multiplying the rows of the first matrix by the columns of the second matrix. Here, the number of columns of the first matrix should be equal to the number of rows of the second matrix. Input and output scenario Suppose we have two matrices A and B. The dimensions of these two matrices are 2X3 and 3X2 respectively. The resulting matrix after multiplication will have 2 rows and 1 column. [b1,b2][a1,a2,a3]*[b3,b4]=[a1*b1+a2*b2+a3*a3][a4,a5,a6][b5,b6][a4*b2+a

Efficient way to reverse multidimensional PHP array Efficient way to reverse multidimensional PHP array Apr 29, 2024 am 09:00 AM

Two effective ways to reverse multidimensional PHP arrays: Recursively using the array_reverse() function: Recursively reverse the elements of each nested array. PHP7's array_reverse() function: Use the new overload of the array_reverse() function to reverse multi-dimensional arrays.

How to use array_walk_recursive function in PHP to perform recursive operations on multi-dimensional arrays How to use array_walk_recursive function in PHP to perform recursive operations on multi-dimensional arrays Jun 26, 2023 am 11:40 AM

Arrays are a very common data type in PHP. Sometimes, we will face situations involving multi-dimensional arrays. In this case, if we need to perform the same operation on all elements, we can use the array_walk_recursive() function. The array_walk_recursive() function is a very powerful recursive function in PHP that can help us perform recursive operations on multi-dimensional arrays. It can recursively traverse each element of a multi-dimensional array and perform corresponding operations on it.

How to sort multidimensional array in PHP How to sort multidimensional array in PHP Jul 07, 2023 pm 12:45 PM

How to sort multi-dimensional arrays in PHP In PHP, arrays are a very common and important data structure, and multi-dimensional arrays are used more frequently in some complex data processing. However, sorting multidimensional arrays can be tricky. This article will show you how to sort multidimensional arrays in PHP and provide specific code examples. Before we begin, let's first understand the structure of multidimensional arrays. Multidimensional array means that the elements in an array are also an array, forming a nested structure. For example: $st

In-depth discussion of PHP arrays: comprehensive analysis of multi-dimensional arrays, associative arrays, etc. In-depth discussion of PHP arrays: comprehensive analysis of multi-dimensional arrays, associative arrays, etc. Mar 13, 2024 pm 02:36 PM

In-depth discussion of PHP arrays: comprehensive analysis of multi-dimensional arrays, associative arrays, etc. Arrays in PHP are a very important data structure that can store multiple data items and access them through indexes. In PHP, arrays can be divided into different types such as indexed arrays, associative arrays, and multidimensional arrays. Each type has its own unique uses and characteristics. This article will delve into the various types of PHP arrays, including how to declare, access, traverse and operate arrays, and will provide specific code examples to help readers better understand. 1. Index array index number

See all articles