如何手动排序(移动)数组元素,反应和/或javascript?

时间:2017-05-29 11:41:26

标签: javascript reactjs

说我有这个数组

arr = ["me", "you", "us", "them"]

我希望能够在点击它时将每个数组元素向上移动一个索引, 例如,当我点击"他们"数组应该像

arr = ["me", "you", "them", "us" ]

我想在理论上使用splice()似乎很简单,但我无法理解它。这是我的代码

    moveRowUp = (to, frm) => {
    const {layout} = this.state
    if(to >= layout.length){
        let diff = to - layout.length;
        while((diff--) + 1){
            layout.push(undefined)
        }
    }
    layout.splice(to, 0, layout.splice(to, 1)[0]);
    // this.setState({
    //     layout: layout
    // })
}

3 个答案:

答案 0 :(得分:2)

为什么不交换两个值,而不是使用拼接?

function moveUp(arr, index) {
  if (index > 0) {
    _swap(arr, index, index - 1);
  }
}

function moveDown(arr, index) {
  if (index < arr.length - 1) {
    _swap(arr, index, index + 1);
  }
}

function _swap(obj, prop1, prop2) {
  var tmp = obj[prop1];
  obj[prop1] = obj[prop2];
  obj[prop2] = tmp;
}

答案 1 :(得分:1)

这将是我使用splice的方法。

const words = ['first', 'second', 'third'];

function click(i) {
  if (i < words.length)
    words.splice(i+1, 0, words.splice(i, 1).pop());
}

click(1);
console.log(words);
.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 2 :(得分:0)

示例:

const a = ["me", "you", "us", "them"];

const moveLeft = arr => word => {
  const i = arr.indexOf(word);
  if (i > -1) {
    arr.splice(i, 1); 
    arr.splice((i !== 0) ? i-1 : arr.length, 0, word) // handle 0 index
  }
  return a;
}

console.log(moveLeft(a)('them'))