Move an array element from one array position to another

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

    I think the best way is define a new property for Arrays

    Object.defineProperty(Array.prototype, 'move', {
        value: function (old_index, new_index) {
            while (old_index < 0) {
                old_index += this.length;
            }
            while (new_index < 0) {
                new_index += this.length;
            }
            if (new_index >= this.length) {
                let k = new_index - this.length;
                while ((k--) + 1) {
                    this.push(undefined);
                }
            }
            this.splice(new_index, 0, this.splice(old_index, 1)[0]);
            return this;
        }
    });
    
    console.log([10, 20, 30, 40, 50].move(0, 1));  // [20, 10, 30, 40, 50]
    console.log([10, 20, 30, 40, 50].move(0, 2));  // [20, 30, 10, 40, 50]
    

提交回复
热议问题