vue.js

关注公众号 jb51net

关闭
首页 > 网络编程 > JavaScript > javascript类库 > vue.js > Vue数组添加元素的实现

Vue数组添加元素的三种实现方式

作者:山间漫步人生路

这篇文章主要介绍了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、删除:删除(任意个数)

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)

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

您可能感兴趣的文章:
阅读全文