Move an array element from one array position to another

后端 未结 30 2474
渐次进展
渐次进展 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:55

    I like this way. It's concise and it works.

    function arraymove(arr, fromIndex, toIndex) {
        var element = arr[fromIndex];
        arr.splice(fromIndex, 1);
        arr.splice(toIndex, 0, element);
    }
    

    Note: always remember to check your array bounds.

    Run Snippet in jsFiddle

提交回复
热议问题