Move an array element from one array position to another

后端 未结 30 2478
渐次进展
渐次进展 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 09:10

        Array.prototype.moveUp = function (value, by) {
            var index = this.indexOf(value),
                newPos = index - (by || 1);
    
            if (index === -1)
                throw new Error("Element not found in array");
    
            if (newPos < 0)
                newPos = 0;
    
            this.splice(index, 1);
            this.splice(newPos, 0, value);
        };
    
        Array.prototype.moveDown = function (value, by) {
            var index = this.indexOf(value),
                newPos = index + (by || 1);
    
            if (index === -1)
                throw new Error("Element not found in array");
    
            if (newPos >= this.length)
                newPos = this.length;
    
            this.splice(index, 1);
            this.splice(newPos, 0, value);
        };
    
    
    
        var arr = ['banana', 'curyWurst', 'pc', 'remembaHaruMembaru'];
    
        alert('withiout changes= '+arr[0]+' ||| '+arr[1]+' ||| '+arr[2]+' ||| '+arr[3]);
        arr.moveDown(arr[2]);
    
    
        alert('third word moved down= '+arr[0] + ' ||| ' + arr[1] + ' ||| ' + arr[2] + ' ||| ' + arr[3]);
        arr.moveUp(arr[2]);
        alert('third word moved up= '+arr[0] + ' ||| ' + arr[1] + ' ||| ' + arr[2] + ' ||| ' + arr[3]);
    

    http://plnkr.co/edit/JaiAaO7FQcdPGPY6G337?p=preview

提交回复
热议问题