📌  相关文章
📜  javascript 移动数组中的元素 - Javascript 代码示例

📅  最后修改于: 2022-03-11 15:03:36.933000             🧑  作者: Mango

代码示例5
function moveArrayItemToNewIndex(arr, old_index, new_index) {
    if (new_index >= arr.length) {
        var k = new_index - arr.length + 1;
        while (k--) {
            arr.push(undefined);
        }
    }
    arr.splice(new_index, 0, arr.splice(old_index, 1)[0]);
    return arr; 
};

//move index 1(b) to index 2(c)
console.log(moveArrayItemToNewIndex(["a","b","c","d"], 1, 2)); // returns ["a", "c", "b", "d"]