2017-05-29 8 views
0

說我有這個數組如何手動排序(移動)周圍的數組元素,在反應和/或JavaScript?

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 
    // }) 
} 
+1

[如何創建一個最小的,完整的,並且可驗證示例](https://stackoverflow.com/help/mcve) – Andreas

+1

你爲什麼不發佈你試圖實現這個目標的代碼? –

+0

有一個很好的笑@andreas。 – Plankton

回答

0

這將是我的方法使用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

而不是使用拼接,爲什麼不交換兩個值?

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; 
} 
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'))