【问题标题】:How to change array element position without swapping in Vuejs? [duplicate]如何在不交换 Vuejs 的情况下更改数组元素位置? [复制]
【发布时间】:2021-12-14 05:47:34
【问题描述】:

groupsCall(callType, params) {
  let url = `/....../`,
    errorMessage = `could not load the items`;

  url =
    callType === "get" ? url + "selected_groups" : url + "update_groups";

  axiosConfig[callType](url, params)
    .then((response) => {
      const data = response.data;
      console.log("hittttt", data.groups_with_selected);

      let tmp = data.groups_with_selected[1];
      data.groups_with_selected[1] = data.groups_with_selected[6];
      data.groups_with_selected[6] = tmp;
      if (isObject(data)) {
        this.setGroupsData(data);
        this.getTotalCount();
        errorMessage = "";
        this.setUpdating(data);
      }
      this.errorMessage = errorMessage;
    })
    .catch((error) => {
      errorMessage = `${errorMessage}. ${error}`;
      this.errorMessage = errorMessage;
      this.updating = false;
    });
},

如何在 Vuejs 中改变数组元素位置而不进行交换?

我使用以下逻辑来交换元素,其中使用以下代码。第 6 位改为第 1 位。第 1 位与第 6 位互换。

 let tmp = data.groups_with_selected[1];
  data.groups_with_selected[1] = data.groups_with_selected[6];
  data.groups_with_selected[6] = tmp;

但这里的问题是,我只想更改数组元素的位置。但是不用换。我不确定如何继续,尝试了很多逻辑。

【问题讨论】:

  • 你想把第六个元素放在数组的顶部,对吗?因此,您将拥有 [6,1,2,3,4,5] 而不是 [1,2,3,4,5,6]
  • 是的,没错。但是想在不交换的情况下更改数组元素的位置。即,第 6 个元素到第 1 个位置。

标签: javascript vue.js axios


【解决方案1】:

如果要将最后一个元素放在数组的顶部,请按照以下方法进行

假设你的数组如下

arr=[6,1,2,3,4,5];

然后你可以做类似的事情

arr.unshift(arr[arr.length-1]);
arr.splice(arr.length-1);

【讨论】:

  • 数组可以有6个以上的元素
  • 是的,解决方案仍然有效
【解决方案2】:

我猜代码没问题,但需要调整:

  1. 您必须通过arr.splice(index, 1) 删除第 6 个位置
  2. 然后通过arr.splice(index, 0, tmp) 插入第一个位置

请看JSSplice

groupsCall(callType, params) {
  let url = `/api/v3/campaigns/${this.campaignId}/`,
    errorMessage = `could not load the filters`;

  url =
    callType === "get" ? url + "selected_groups" : url + "update_groups";

  axiosConfig[callType](url, params)
    .then((response) => {
      const data = response.data;
      console.log("hittttt", data.groups_with_selected);

      let tmp = data.groups_with_selected[6];
      // Remove the 6th position
      data.groups_with_selected.splice(6, 1)
      // Insert tmp 
      data.groups_with_selected.splice(1, 0, tmp)
      // This code is not needed
      // data.groups_with_selected[6] = tmp;
      if (isObject(data)) {
        this.setGroupsData(data);
        this.getTotalCount();
        errorMessage = "";
        this.setUpdating(data);
      }
      this.errorMessage = errorMessage;
    })
    .catch((error) => {
      errorMessage = `${errorMessage}. ${error}`;
      this.errorMessage = errorMessage;
      this.updating = false;
    });
},

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-09-13
    • 2019-08-13
    • 2021-06-09
    • 2014-12-10
    • 1970-01-01
    • 2021-03-31
    • 2011-05-05
    相关资源
    最近更新 更多