数组(Array)是一种用来存储多个值的有序集合。在JavaScript中,数组可以包含任意类型的数据,包括原始数据类型和其他对象。
创建数组的方式有多种,常见的方式包括:
- 数组字面量:
const array = [1, 2, "张三", "李四"];
- 使用new关键字和Array构造函数创建数组:
const array = new Array(1, 2, "张三", "李四");
可以通过索引访问数组中的元素,使用方括号([])加上索引值。
数组的每个值称为元素(Element),元素存储在数组中的特定位置,位置称为索引(Index)。索引从0开始,依次递增。
const array = ["apple", "banana", "orange"];
console.log(array[0]); // 输出 "apple"
console.log(array[1]); // 输出 "banana"
数组有许多内置的属性和方法,可以用于处理和操作数组。常见的属性和方法包括:
- length:返回数组中元素的个数。
- push():向数组末尾添加一个元素。
- pop():删除并返回数组中的最后一个元素。
- shift():删除并返回数组中的第一个元素。
- unshift():向数组开头添加一个或多个元素。
- concat():合并两个或多个数组,返回新的数组。
- slice():返回指定起始索引和结束索引之间的一个片段。
- splice():修改数组,删除、替换或插入元素。
- indexOf():返回第一个匹配元素的索引。
- forEach():对数组中的每个元素执行指定的函数。
除了上述方法,还有许多其他的方法可以用于数组的遍历、搜索、排序等操作。
数组是JavaScript中最常用的数据结构之一,它提供了一种有序存储多个值的方式。使用数组,可以更方便地处理和操作多个相关的数据。在实际开发中,数组经常用于存储列表、追踪数据集合的变化、进行数据的聚合和计算等。
以下是一些常见的数组内置属性和方法的示例代码:
const fruits = ["apple", "banana", "orange"];
console.log(fruits.length); // 输出 3
fruits.push("grape"); // 向数组末尾添加一个元素
console.log(fruits); // 输出 ["apple", "banana", "orange", "grape"]
const lastElement = fruits.pop(); // 删除并返回数组中的最后一个元素
console.log(lastElement); // 输出 "grape"
console.log(fruits); // 输出 ["apple", "banana", "orange"]
const firstElement = fruits.shift(); // 删除并返回数组中的第一个元素
console.log(firstElement); // 输出 "apple"
console.log(fruits); // 输出 ["banana", "orange"]
fruits.unshift("kiwi", "mango"); // 向数组开头添加一个或多个元素
console.log(fruits); // 输出 ["kiwi", "mango", "banana", "orange"]
const slicedElements = fruits.slice(1, 3); // 返回索引1至2之间的一个片段
console.log(slicedElements); // 输出 ["mango", "banana"]
fruits.splice(1, 1, "grapefruit"); // 替换索引为1的元素为"grapefruit"
console.log(fruits); // 输出 ["kiwi", "grapefruit", "banana", "orange"]
const bananaIndex = fruits.indexOf("banana"); // 返回"banana"的索引
console.log(bananaIndex); // 输出 2
fruits.forEach(function(fruit) { // 对每个元素执行指定函数
console.log(fruit);
});
// 输出:
// kiwi
// grapefruit
// banana
// orange