Home > Web Front-end > JS Tutorial > body text

Introduction to common operation methods of js array

王林
Release: 2020-04-28 09:27:49
forward
2794 people have browsed it

Introduction to common operation methods of js array

Arrays and operation methods

An array is a collection of data. In JavaScript, the data in the array can be of different types.

Methods to define arrays

//对象的实例创建
var aList = new Array(1,2,3);
//直接量创建
var aList2 = [1,2,3,'asd'];
Copy after login

Methods to operate data in arrays

1. Get the length of the array: aList.length;

var aList = [1,2,3,4];
alert(aList.length); // 弹出4
Copy after login

2. Use Subscript operates on a certain data in the array: aList[0];

var aList = [1,2,3,4];
alert(aList[0]); // 弹出1
Copy after login

3. join() merges the array members into a string through a separator

var aList = [1,2,3,4];
alert(aList.join('-')); // 弹出 1-2-3-4
Copy after login

4. push() and pop() adds or deletes members from the end of the array

var aList = [1,2,3,4];
aList.push(5);
alert(aList); //弹出1,2,3,4,5
aList.pop();
alert(aList); // 弹出1,2,3,4
Copy after login

5, unshift() and shift() adds or deletes members from the front of the array

var aList = [1,2,3,4];
aList.unshift(5);
alert(aList); //弹出5,1,2,3,4
aList.shift();
alert(aList); // 弹出1,2,3,4
Copy after login

6, reverse() reverses the array Turn

var aList = [1,2,3,4];
aList.reverse();
alert(aList); // 弹出4,3,2,1
Copy after login

7. indexOf() returns the index value of the first occurrence of the element in the array

var aList = [1,2,3,4,1,3,4];
alert(aList.indexOf(1));
Copy after login

8. splice() adds or deletes members from the array

var aList = [1,2,3,4];
aList.splice(2,1,7,8,9); //从第2个元素开始,删除1个元素,然后在此位置增加'7,8,9'三个元素
alert(aList); //弹出 1,2,7,8,9,4
Copy after login

Multidimensional array

Multidimensional array refers to an array whose members are also arrays.

var aList = [[1,2,3],['a','b','c']];
 
alert(aList[0][1]); //弹出2;
Copy after login

Recommended tutorial: js introductory tutorial

The above is the detailed content of Introduction to common operation methods of js array. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:jb51.net
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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!