Vue数组添加元素的三种实现方式
更新时间:2025年09月15日 10:35:41 作者:山间漫步人生路
这篇文章主要介绍了Vue数组添加元素的三种实现方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
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)
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
相关文章
从0搭建Vue3组件库如何使用 glup 打包组件库并实现按需加载
这篇文章主要介绍了从0搭建Vue3组件库如何使用 glup 打包组件库并实现按需加载,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下2023-03-03
Electron-Vite + Vue 3 项目中实现流畅触底加载更多功能
本文介绍在Electron-Vite+Vue3项目中实现触底加载的两种方式:原生滚动监听和vue-infinite-loading库,下面给大家分享详细实现步骤,感兴趣的朋友一起看看吧2025-07-07
Vuex unknown action type报错问题及解决
这篇文章主要介绍了Vuex unknown action type报错问题及解决方案,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教2023-02-02


最新评论