定义:
splice() 方法向/从数组中添加/删除项目,然后返回被删除的项目。
注释:
该方法会改变原始数组。
1.增加数据:
在本例中,我们将创建一个新数组,并向其添加一个元素:
<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 + "
")
arr.splice(2,0,"William")
document.write(arr + "
")
</script>
运行结果:
George,John,Thomas,James,Adrew,Martin
George,John,William,Thomas,James,Adrew,Martin
2.删除数据:
在本例中我们将删除位于 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 + "
")
arr.splice(2,1,"William")
document.write(arr)
</script>
运行结果:
George,John,Thomas,James,Adrew,Martin
George,John,William,James,Adrew,Martin
3.增加+删除数据 同时进行:
在本例中我们将删除从 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 + "
")
arr.splice(2,3,"William")
document.write(arr)
</script>
运行结果:
George,John,Thomas,James,Adrew,Martin
George,John,William,Martin
4.增加+删除数据 Vue实例:
在本例中我们点击添加,添加新的数字,点击删除,删除数组的数据
HTML
<div id="list-demo" class="demo">
<button v-on:click="add">Add</button>
<button v-on:click="remove">Remove</button>
<transition-group name="list" tag="p">
<span v-for="item in items" v-bind:key="item" class="list-item">
{{ item }}
</span>
</transition-group>
</div>
Vue
new Vue({
el: '#list-demo',
data: {
items: [1,2,3,4,5,6,7,8,9],
nextNum: 10
},
methods: {
randomIndex: function () {
return Math.floor(Math.random() * this.items.length)
},
add: function () {
this.items.splice(this.randomIndex(), 0, this.nextNum++)
},
remove: function () {
this.items.splice(this.randomIndex(), 1)
},
}
})
CSS
.list-item {
display: inline-block;
margin-right: 10px;
}
.list-enter-active, .list-leave-active {
transition: all 1s;
}
.list-enter, .list-leave-to
/* .list-leave-active for below version 2.1.8 */ {
opacity: 0;
transform: translateY(30px);
}