【Vue】数组添加元素的三种方式

本文介绍了JavaScript中数组的三种常用操作:push()用于在数组末尾添加元素,unshift()用于在数组开头添加元素,而splice()方法则能实现添加和删除元素的灵活操作。通过实例演示了每个方法的具体用法,帮助读者掌握数组操作技巧。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、push() 结尾添加

数组.push(元素)

var node1 = ['111','222']
var new_node = node1.push('aaa')

此时数据为
node1: ['111','222','aaa']

2、unshift() 头部添加

数组.unshift(元素)

var node1 = ['111','222']
var new_node = node1.unshift('aaa')

此时数据为
node1: ['aaa','111','222']

3、splice() 方法向/从数组指定位置添加/删除项目,然后返回被删除的项目。

参数描述
index必需。整数,规定添加/删除项目的位置,使用负数可从数组结尾处规定位置。
howmany必需。要删除的项目数量。如果设置为 0,则不会删除项目。
item1, …, itemX可选。向数组添加的新项目。
 /**
     * Removes elements from an array and, if necessary, inserts new elements in their place, returning the deleted elements.
     * @param start The zero-based location in the array from which to start removing elements.
     * @param deleteCount The number of elements to remove.
     * @returns An array containing the elements that were deleted.
     */
    splice(start: number, deleteCount?: number): T[];
    /**
     * Removes elements from an array and, if necessary, inserts new elements in their place, returning the deleted elements.
     * @param start The zero-based location in the array from which to start removing elements.
     * @param deleteCount The number of elements to remove.
     * @param items Elements to insert into the array in place of the deleted elements.
     * @returns An array containing the elements that were deleted.
     */
    splice(start: number, deleteCount: number, ...items: T[]): T[];

例如

1、删除:删除(任意个数)
参数1:开始的索引;参数2:删除的长度
var node = ['11','22','33','44']
var new_node = node.splice(1,2)
//返回被删除的数组元素
//new_node  输出 ['22','33']
console.log(new_node )
//node输出 ['11','44']
console.log(node)

2、添加(任意个数): 插入起始位置、0(要删除的项数)和要插入的项(不限)
var node = ['11','22','33','44']
//添加splice(start,0,newInfo)--返回值为空数组
var new_node = node.splice(1,0,'aa','bb')
// new_node 输出 []
console.log(new_node)
// node 输出 ['11', 'aa', 'bb', '22', '33', '44']
console.log(node)



评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

山间漫步人生路

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值