在JavaScript中,数组是一种数据结构,用来储存多个值的列表。它是一种有序的集合,可以通过数字索引来访问数组中的每个元素。数组中的每个元素可以是任意类型的数据,包括数字、字符串、对象等。
在JavaScript中创建数组有两种方式:
使用数组字面量(Array Literal)创建数组。数组字面量是一对方括号中的元素列表,每个元素之间用逗号隔开。
let myArray = [1, 2, 3, "hello", true];
使用Array构造函数创建数组。Array构造函数可以接受一个或多个参数(可以是任意类型),用来初始化数组元素。
let myArray = new Array(1, 2, 3, "hello", true);
访问数组元素时,可以使用方括号加上索引访问数组中的元素,索引从0开始:
console.log(myArray[0]); // 1
console.log(myArray[3]); // "hello"
还可以使用数组的一些内置方法来操作数组,比如添加、删除、排序、过滤等。以下是一些常用的数组方法:
push:向数组末尾添加一个或多个元素。
myArray.push(4, 5);
console.log(myArray); // [1, 2, 3, "hello", true, 4, 5]
pop:从数组末尾移除最后一个元素。
myArray.pop();
console.log(myArray); // [1, 2, 3, "hello", true, 4]
shift:从数组开头移除第一个元素。
myArray.shift();
console.log(myArray); // [2, 3, "hello", true, 4]
unshift:向数组开头添加一个或多个元素。
myArray.unshift("first", "second");
console.log(myArray); // ["first", "second", 2, 3, "hello", true, 4]
splice:从数组中删除指定位置的元素,并可在指定位置插入新元素。
myArray.splice(2, 1, "new"); // 从索引为2的位置删除1个元素,然后在该位置插入"new"
console.log(myArray); // ["first", "second", "new", 3, "hello", true, 4]
sort:对数组进行排序,默认为按字母顺序排序,也可以指定自定义排序函数。
myArray.sort();
console.log(myArray); // [3, 4, "first", "hello", "new", "second", true]
filter:过滤满足条件的元素,返回一个新的数组。
let filteredArray = myArray.filter(element => typeof element === "number");
console.log(filteredArray); // [3, 4]
数组翻转
let arr = [1, 2, 3, 4, 5];
arr.reverse(); // [5, 4, 3, 2, 1]
数组拼接
let arr1 = ["a", "b", "c"];
let arr2 = ["d", "e", "f"];
let arr3 = arr1.concat(arr2); // ["a", "b", "c", "d", "e", "f"]
数组截取
let arr = ["a", "b", "c", "d", "e", "f"];
let newArr = arr.slice(1, 4); // ["b", "c", "d"]
数组删除
let arr = ["a", "b", "c", "d", "e", "f"];
let deletedArr = arr.splice(2, 3); // ["c", "d", "e"]
console.log(arr); // ["a", "b", "f"]
数组插入
let arr = ["a", "b", "c", "d", "e", "f"];
arr.splice(2, 0, "x", "y"); // 在索引为2的位置插入"x"和"y"
console.log(arr); // ["a", "b", "x", "y", "c", "d", "e", "f"]
数组替换
let arr = ["a", "b", "c", "d", "e", "f"];
arr.splice(2, 2, "x", "y"); // 从索引为2的位置开始,删除2个元素,然后插入"x"和"y"
console.log(arr); // ["a", "b", "x", "y", "e", "f"]