splice 应用上移下移
语法
array.splice(index,howmany,item1,.....,itemX)
参数 Values
| 参数 | 描述 |
|---|---|
| index | 必需。规定从何处添加/删除元素。 该参数是开始插入和(或)删除的数组元素的下标,必须是数字。 |
| howmany | 可选。规定应该删除多少元素。必须是数字,但可以是 "0"。 如果未规定此参数,则删除从 index 开始到原数组结尾的所有元素。 |
| item1, ..., itemX | 可选。要添加到数组的新元素 |
返回值
| Type | 描述 |
|---|---|
| Array | 如果从 arrayObject 中删除了元素,则返回的是含有被删除的元素的数组。 |
在前端开发中,类似下面的效果(数据的上移和下移)前端会经常遇到,接下来看下这个一行神奇的js代码
为了方便jym理清思路 我特意把这个方法拆开了
// 图片是我当时的业务代码下面这个方法是抽取的公共的方法
/**
1. type 为0 上移, 1 为下移
2. index 为需要移动的 数组的下标
3. eventList 是需要移动的目标数组
**/
changeSort(index, type) {
let fItem=this.eventList[ type ? index : index - 1]
let data=this.eventList.splice(type ? index + 1 : index,1, fItem )
this.eventList.splice(type ? index : index - 1, 1, ...data)
}
希望大家百尺竿头更进一步