数组的变更方法(如 push(item)
、pop()
、shift()
、unshift(item)
、splice(index, count, ...items)
、sort()
和 reverse()
)用于直接修改数组的内容。以下是这些方法的详细用途和示例:
1. push(item)
- 用途:在数组的末尾添加一个或多个元素。
- 返回值:返回数组的新长度。
- 示例:
const fruits = ['apple', 'banana'];
fruits.push('orange');
console.log(fruits); // 输出: ['apple', 'banana', 'orange']
2. pop()
- 用途:移除数组的最后一个元素,并返回该元素。
- 返回值:被移除的元素。
- 示例:
const fruits = ['apple', 'banana', 'orange'];
const removedFruit = fruits.pop();
console.log(removedFruit); // 输出: 'orange'
console.log(fruits); // 输出: ['apple', 'banana']
3. shift()
- 用途:移除数组的第一个元素,并返回该元素。
- 返回值:被移除的元素。
- 示例:
const fruits = ['apple', 'banana', 'orange'];
const removedFruit = fruits.shift();
console.log(removedFruit); // 输出: 'apple'
console.log(fruits); // 输出: ['banana', 'orange']
4. unshift(item)
- 用途:在数组的开头添加一个或多个元素。
- 返回值:返回数组的新长度。
- 示例:
const fruits = ['banana', 'orange'];
fruits.unshift('apple');
console.log(fruits); // 输出: ['apple', 'banana', 'orange']
5. splice(index, count, ...items)
- 用途:通过删除或替换现有元素或添加新元素来修改数组。
- 参数:
index
:开始修改的索引位置。count
:要移除的元素个数。...items
:可选,要添加到数组的新元素。
- 返回值:包含被移除元素的数组。
- 示例:
const fruits = ['apple', 'banana', 'orange', 'grape'];
// 从索引 1 开始,移除 2 个元素,并添加 'pear' 和 'peach'
const removedFruits = fruits.splice(1, 2, 'pear', 'peach');
console.log(removedFruits); // 输出: ['banana', 'orange']
console.log(fruits); // 输出: ['apple', 'pear', 'peach', 'grape']
6. sort()
- 用途:对数组的元素进行排序,并返回排序后的数组。
- 注意:默认按 Unicode 码点排序,通常需要传入比较函数来正确排序数字或自定义排序。
- 返回值:排序后的数组。
- 示例:
const numbers = [3, 1, 4, 1, 5];
numbers.sort((a, b) => a - b); // 升序排序
console.log(numbers); // 输出: [1, 1, 3, 4, 5]
7. reverse()
- 用途:反转数组中元素的顺序。
- 返回值:反转后的数组。
- 示例:
const fruits = ['apple', 'banana', 'orange'];
fruits.reverse();
console.log(fruits); // 输出: ['orange', 'banana', 'apple']
总结
这些方法都直接修改原数组(除了 sort()
和 reverse()
的返回值是原数组本身,但原数组也已被修改),而不是返回一个新数组。在 Vue 3 的响应式系统中,使用这些方法修改数组会触发视图更新,因为 Vue 3 已经对这些方法进行了响应式处理。
push
和unshift
:用于添加元素。pop
和shift
:用于移除元素。splice
:用于删除、替换或添加元素。sort
:用于排序元素。reverse
:用于反转元素顺序。