【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)



你可能感兴趣的:(VUE,vue,javascript,数组,js)