在JavaScript(JS)中,列表通常指的是数组(Array)。数组是一种特殊的对象,用于存储一系列有序的值。每个值都有一个与之关联的数字,称为索引,用于标识该值在数组中的位置。
基础概念:
[10, 20, 30]
中,10
的索引是0
,20
的索引是1
,30
的索引是2
。length
)表示数组中元素的数量。在上述例子中,数组的长度是3
。优势:
push
、pop
、shift
、unshift
、splice
等,方便对数组进行操作。类型:
应用场景:
常见问题及解决方法:
undefined
值。要避免这种情况,可以检查索引是否在有效范围内(0
到数组长度 - 1
)。delete
操作符删除数组中的元素,会留下空位(即undefined
值占据的位置)。可以使用splice
方法来删除元素并移动后续元素以填补空位。for...in
循环遍历数组时。要避免这种情况,可以使用for
循环或Array.prototype.forEach
方法来遍历数组。示例代码:
// 创建一个数组
let fruits = ['apple', 'banana', 'cherry'];
// 访问数组中的元素
console.log(fruits[0]); // 输出 'apple'
console.log(fruits[1]); // 输出 'banana'
console.log(fruits[2]); // 输出 'cherry'
// 修改数组中的元素
fruits[1] = 'orange';
console.log(fruits); // 输出 ['apple', 'orange', 'cherry']
// 添加新元素到数组末尾
fruits.push('grape');
console.log(fruits); // 输出 ['apple', 'orange', 'cherry', 'grape']
// 删除数组中的元素
fruits.splice(1, 1); // 从索引1开始删除1个元素
console.log(fruits); // 输出 ['apple', 'cherry', 'grape']
// 遍历数组
fruits.forEach(function(fruit) {
console.log(fruit);
});
输出:
apple
banana
cherry
apple
orange
cherry
grape
apple
cherry
grape
领取专属 10元无门槛券
手把手带您无忧上云