js change position of the element in the array - exchange, top, up, down

unshift () method to add one or more elements to the beginning of the array, and returns the new length.

shift () method is used to remove the first element of the array from which, and returns the value of the first element.

splice () method can remove zero or more elements from the beginning of the index, and to replace those removed element with one or more values ​​of the parameters declared in the list.

One, two elements Commutator

function swapArr(arr, index1, index2) {
    arr[index1] = arr.splice(index2, 1, arr[index1])[0];
    return arr;
}

Second, the top mobile


function toFirst(fieldData,index) {
 
    if(index!=0){
 
        // fieldData[index] = fieldData.splice(0, 1, fieldData[index])[0]; 这种方法是与另一个元素交换了位子,
 
        fieldData.unshift(fieldData.splice(index , 1)[0]);
 
    }
 


Third, moving up on a grid


function upGo(fieldData,index){
 
    if(index!=0){
 
        fieldData[index] = fieldData.splice(index-1, 1, fieldData[index])[0];
 
    }else{
 
        fieldData.push(fieldData.shift());
 
    }
 
}

Fourth, the move down one space

function downGo(fieldData,index) {
 
    if(index!=fieldData.length-1){
 
        fieldData[index] = fieldData.splice(index+1, 1, fieldData[index])[0];
 
    }else{
 
        fieldData.unshift( fieldData.splice(index,1)[0]);
 
    }
 
}

Article: https: //www.joynop.com/p/174.html

Published 24 original articles · won praise 11 · views 50000 +

Guess you like

Origin blog.csdn.net/mehnr/article/details/104554418