• splice——替换功能,第一个参数(起始位置),第二个参数(删除的项数),第三个参数(插入任意数量的项)。
    • 用法:array.splice(index,num,insertValue),返回值为删除内容,array为结果值。
    1. moveUp(index) {
    2. if (index === 0) {
    3. return
    4. }
    5. util.moveUp(this.templates, index)
    6. },
    7. moveDown(index) {
    8. if (index === (this.templates.length - 1)) {
    9. return
    10. }
    11. util.moveDown(this.templates, index)
    12. }
    1. swapArray(arr, index1, index2) {
    2. console.log('数组', arr)
    3. console.log('原下标', index1) // 1
    4. console.log('新下标', index2) // 0
    5. arr[index1] = arr.splice(index2, 1, arr[index1])[0]
    6. console.log('操作', arr[index1])
    7. return arr
    8. },
    9. // 上移 将当前数组index索引与后面一个元素互换位置,向数组后面移动一位
    10. moveUp(arr, index) {
    11. this.swapArray(arr, index, index - 1)
    12. },
    13. // 下移 将当前数组index索引与前面一个元素互换位置,向数组前面移动一位
    14. moveDown(arr, index) {
    15. this.swapArray(arr, index, index + 1)
    16. },

    如何实现换位? 1 、2 、3(index2) 、4(index1)===> 1 2 4 3;

    1. arr.splice(index2, 1, arr[index1])[0] ====> 1 、2 、4 、4 ====> return 返回被删除的结果 “3”
    2. 数组第四个 arr[index1] = 3
    3. 1244 == >1243