Move an array element from one array position to another

后端 未结 30 2490
渐次进展
渐次进展 2020-11-22 08:36

I\'m having a hard time figuring out how to move an array element. For example, given the following:

var arr = [ \'a\', \'b\', \'c\', \'d\', \'e\'];
<         


        
30条回答
  •  无人及你
    2020-11-22 08:51

    The splice() method adds/removes items to/from an array, and returns the removed item(s).

    Note: This method changes the original array. /w3schools/

    Array.prototype.move = function(from,to){
      this.splice(to,0,this.splice(from,1)[0]);
      return this;
    };
    
    var arr = [ 'a', 'b', 'c', 'd', 'e'];
    arr.move(3,1);//["a", "d", "b", "c", "e"]
    
    
    var arr = [ 'a', 'b', 'c', 'd', 'e'];
    arr.move(0,2);//["b", "c", "a", "d", "e"]
    

    as the function is chainable this works too:

    alert(arr.move(0,2).join(','));
    

    demo here

提交回复
热议问题