js实现数组顺序替换

1,103 阅读1分钟

前言

  • 大家好,我是_Peach,今天来分享下数组顺序替换
  1. 今天测试同事像我提出了一个问题,
  2. 要实现自定义数组索引位置,我心想数据都是从接口返回的,排序它干嘛,
  3. 测试同事表示,需要把收费项,以及其他规则,可以自定义位置,随意放到数组任一位置,优化用户体验
  4. 于是我打开vscode,使用了一段js代码写入进去,于是实现了数据排序,交给测试同事点点点,搞定,下班!

image.png

下班回来之后,因为最近有在学习Vue3,想着用Vue3的语法来写个demo,也算是记录自己的学习笔记,方便下次使用的时候容易查找

本期使用到的知识点

  • Vue3 ref
  • setup语法糖
  • 数组方法

splice()  方法通过删除或替换现有元素或者原地添加新的元素来修改数组,并以数组形式返回被修改的内容。此方法会改变原数组

unshift()  方法将一个或多个元素添加到数组的开头,并返回该数组的新长度(该方法修改原有数组)。

push()  方法将一个或多个元素添加到数组的末尾,并返回该数组的新长度。

实现思路

  1. splice可实现 从索引的位置开始删除 1 个元素,插入元素 并且返回被删除的数据
<script>
// 先将目标位置 进行替换 返回值是被删除的元素 此时再将返回的元素赋值给源位置 实现了数组位置替换
  const result = array.splice(target, 1, array[source]);
  array[source] = result[0];
</script>
  1. 此时再将返回的元素赋值给源位置 实现了数组位置替换

完整代码

<template>
  <div>
    <div v-for="(item, index) in state"
         class="el-crad"
         :key="item.id">
      <div>
        <h2>{{ item.id }} --- {{ item.name }}</h2>
        <button @click="topElment(index)"></button> <span> </span>
        <button @click="bottomElment(index)"></button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref } from "vue";
const state = ref([]);
state.value = [
  {
    id: 1,
    name: "peach1",
  },
  {
    id: 2,
    name: "peach2",
  },
  {
    id: 3,
    name: "peach3",
  },
];
console.log(state.value);
// 顺序上移
const topElment = (index) => {
  changeIndex(state.value, index, --index);
};
// 顺序下移
const bottomElment = (index) => {
  changeIndex(state.value, index, ++index);
};
// array:数组 source:源位置 target目标位置
function changeIndex (array, source, target) {
  // 到达底部时候 向数组前面插入 并删除最后一位
  if (array.length == target) {
    array.unshift(array[source]);
    array.splice(array.length - 1, 1);
    return;
  }
  // 当索引为0时 --index 等于 -1 表示 要push到最后一位 然后将第一位删除
  if (target == -1) {
    array.push(array[0]);
    array.splice(0, 1);
    return;
  }
  // 先将目标位置 进行替换 返回值是被删除的元素 此时再将返回的元素赋值给源位置 实现了数组位置替换
  // const result = array.splice(target, 1, array[source]);
  // array[source] = result[0];
  // 简洁写法
  array[source] = array.splice(target, 1, array[source])[0];
}
</script>

<style lang="less" scoped>
.el-crad {
  margin: 20px 0;
  padding: 25px;
  height: 120px;
  border: 1px solid #ccc;
  border-radius: 20px;
}
.el-crad:hover {
  box-shadow: 0 2px 12px 0 rgb(#bebebe);
}
</style>