其他分享
首页 > 其他分享> > Vue中splice的运用

Vue中splice的运用

作者:互联网

转自https://blog.csdn.net/qq_42043377/article/details/83003159
感谢博主分享,真是让人秒懂哇~


其实说白了 vue中的splice和javaScript中的是一样的

splice(index,len,[item])它也可以用来替换/删除/添加数组内某一个或者几个值(该方法会改变原始数组

index:数组开始下标

len: 替换/删除的长度

item:替换的值,删除操作的话 item为空


举个例子:

在本例中,我们将创建一个新数组,并向其添加一个元素:

<script type="text/javascript">

var arr = new Array(6)
arr[0] = "George"
arr[1] = "John"
arr[2] = "Thomas"
arr[3] = "James"
arr[4] = "Adrew"
arr[5] = "Martin"

document.write(arr + "<br />")
arr.splice(2,0,"William")

document.write(arr + "<br />")

</script>

输出:

George,John,Thomas,James,Adrew,Martin
George,John,William,Thomas,James,Adrew,Martin

在本例中我们将删除位于 index 2 的元素,并添加一个新元素来替代被删除的元素:

<script type="text/javascript">

var arr = new Array(6)
arr[0] = "George"
arr[1] = "John"
arr[2] = "Thomas"
arr[3] = "James"
arr[4] = "Adrew"
arr[5] = "Martin"

document.write(arr + "<br />")
arr.splice(2,1,"William")

document.write(arr)

</script>

输出:

George,John,Thomas,James,Adrew,Martin
George,John,William,James,Adrew,Martin

在本例中我们将删除从 index 2 (“Thomas”) 开始的三个元素,并添加一个新元素 (“William”) 来替代被删除的元素:

<script type="text/javascript">

var arr = new Array(6)
arr[0] = "George"
arr[1] = "John"
arr[2] = "Thomas"
arr[3] = "James"
arr[4] = "Adrew"
arr[5] = "Martin"

document.write(arr + "<br />")
arr.splice(2,3,"William")

document.write(arr)

</script>

输出:

George,John,Thomas,James,Adrew,Martin
George,John,William,Martin

这个例子是删除全部

<script type="text/javascript">

var arr = new Array(6)
arr[0] = "George"
arr[1] = "John"
arr[2] = "Thomas"
arr[3] = "James"
arr[4] = "Adrew"
arr[5] = "Martin"

document.write(arr + "<br />")
arr.splice(0,arr.length)

document.write(arr)

</script>

输出:

  什么都没有

相信大家到这已经懂了 祝你们学业有成

标签:arr,Vue,James,Adrew,splice,Martin,运用,John,George
来源: https://blog.csdn.net/weixin_40688217/article/details/89817475