Home >Web Front-end >JS Tutorial >JavaScript Array usage guide
Detailed explanation of Array in JavaScript
JavaScript is a programming language widely used in Web development, and it has powerful data processing capabilities. In JavaScript, Array is a very commonly used data structure used to store and manipulate a set of data. This article will delve into the various methods and usage of Array in JavaScript, and deepen understanding through specific code examples.
var arr1 = []; // 创建一个空数组 var arr2 = [1, 2, 3]; // 创建一个包含三个元素的数组 var arr3 = ['a', 'b', 'c']; // 创建一个包含三个字符串的数组
var arr4 = new Array(); // 创建一个空数组 var arr5 = new Array(1, 2, 3); // 创建一个包含三个元素的数组 var arr6 = new Array('a', 'b', 'c'); // 创建一个包含三个字符串的数组
var arr = ['apple', 'banana', 'cherry']; console.log(arr[0]); // 输出:'apple' arr[1] = 'orange'; console.log(arr); // 输出:['apple', 'orange', 'cherry'] console.log(arr.length); // 输出:3
var arr = [1, 2, 3]; arr.push(4); console.log(arr); // 输出:[1, 2, 3, 4] arr.pop(); console.log(arr); // 输出:[1, 2, 3]
var arr = [1, 2, 3]; arr.shift(); console.log(arr); // 输出:[2, 3] arr.unshift(0); console.log(arr); // 输出:[0, 2, 3]
var arr = [1, 2, 3, 4, 5]; var subArr = arr.slice(1, 4); console.log(subArr); // 输出:[2, 3, 4] arr.splice(1, 2, 'a', 'b'); console.log(arr); // 输出:[1, 'a', 'b', 4, 5]
var arr1 = [1, 2]; var arr2 = [3, 4]; var newArray = arr1.concat(arr2); console.log(newArray); // 输出:[1, 2, 3, 4]
var arr = [1, 2, 3, 2, 4]; console.log(arr.indexOf(2)); // 输出:1 console.log(arr.lastIndexOf(2)); // 输出:3
There are many other array methods, such as join(), reverse(), sort(), etc., which can be learned and used according to actual needs.
Summary:
This article deeply explores the various methods and usage of Array in JavaScript, and deepens its understanding through specific code examples. With this knowledge, you can handle array-related tasks more flexibly and efficiently. In actual development, array operations are an indispensable part. I hope this article can help readers use Array in JavaScript.
The above is the detailed content of JavaScript Array usage guide. For more information, please follow other related articles on the PHP Chinese website!