【问题标题】:How to shift first element of the array on different different indexes in javascript [duplicate]如何在javascript中的不同索引上移动数组的第一个元素[重复]
【发布时间】:2019-03-06 15:00:07
【问题描述】:

我的数组是:

var array = ["author", "1", "2", "3", "5", "6"]

我正在尝试通过单击按钮将作者移动到数组的第一个位置,而不是数组的第二个位置和末尾。

【问题讨论】:

  • 嗯?你试过什么?
  • 你能描述一下第一次点击按钮后数组应该是什么样子吗?
  • 点击按钮后数组应该看起来像 var array = ["1", "author", "2", "3", "4", "5", "6"] /跨度>

标签: javascript


【解决方案1】:

您可以关闭索引以与下一个交换并检查交换是否可能。如果不返回数组,则交换元素。

const
    swap = (a, i = 0) => () => {
        if (i + 1 >= a.length) return a;
        [a[i + 1], a[i]] = [a[i], a[i +  1]];
        i++;
        return a;
    };

var array = ["author", "1", "2", "3", "5", "6"],
    s = swap(array);

console.log(...array);
console.log(...s());
console.log(...s());
console.log(...s());
console.log(...s());
console.log(...s());
console.log(...s());
如果您不喜欢解构和分配值,则可以改用splice,它从以下索引扩展拼接数组,长度为一项。

const
    swap = (a, i = 0) => () => {
        a.splice(i, 0, ...a.splice(++i, 1));
        return a;
    };

var array = ["author", "1", "2", "3", "5", "6"],
    s = swap(array);

console.log(...array);
console.log(...s());
console.log(...s());
console.log(...s());
console.log(...s());
console.log(...s());
console.log(...s());

【讨论】:

    【解决方案2】:

    点击按钮获取indexOf作者并在另一个变量中获取下一个索引处的元素。如果数组中的下一个位置不是undefined,则将author 的位置与紧邻的下一个元素互换

    var array = ["author", "1", "2", "3", "5", "6"]
    
    
    function shiftAuthor() {
      // get index of author in the array
      let currPosition = array.indexOf('author');
      // if the index of author +1 is not undefined
      if (array[currPosition + 1] !== undefined) {
        // get the element at the next index of author
        let elemAtNextPos = array[currPosition + 1];
        // interchange their position
        array[currPosition + 1] = 'author'
        array[currPosition] = elemAtNextPos;
      }
      console.log(array)
    }
    <button type='button' onclick='shiftAuthor()'> Shift Author </button>

    【讨论】:

    • @Shreyashukla 它是同一个数组
    猜你喜欢
    • 2018-03-21
    • 2018-04-06
    • 2023-01-07
    • 2021-10-27
    • 1970-01-01
    • 2021-08-23
    • 2016-09-27
    • 2018-11-07
    • 2020-11-27
    相关资源
    最近更新 更多