Home  >  Article  >  Web Front-end  >  Introduction to common operation methods of js array

Introduction to common operation methods of js array

王林
王林forward
2020-04-28 09:27:492807browse

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'];

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

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

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

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

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

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

6, reverse() reverses the array Turn

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

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));

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

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;

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!

Statement:
This article is reproduced at:jb51.net. If there is any infringement, please contact admin@php.cn delete