JS数组移动元素

JS arrays shifting elements around

本文关键字:元素 移动 数组 JS      更新时间:2023-09-26

当涉及到JS数组/对象时,我不是那么好,所以我现在有以下内容:

{
    "rows":{
        "0":{
            "type":"row",
            "width_class":"row new_row",
            "column_class":"one"
        },
        "1":{
            "type":"row",
            "width_class":"row new_row",
            "column_class":"two"
        },
        "2":{
            "type":"row",
            "width_class":"row new_row",
            "column_class":"three"        
        }
    }
}

现在我要完成的是移动行,例如将"1"移动到"0"的位置,然后重新执行键,使它们从0到总计数(-1)。

有谁能帮我吗?

使用Array.splice() API删除第一个元素

如果你的对象看起来像这样:

{
  "rows": [
    {
        "type":"row",
        "width_class":"row new_row",
        "column_class":"one"
    },
    {
        "type":"row",
        "width_class":"row new_row",
        "column_class":"two"
    },
    {
        "type":"row",
        "width_class":"row new_row",
        "column_class":"three"        
    }
  ]
};

您可以使用Array方法来拖动[yourobj].rows的元素。

这里有一个JsFiddle的例子