【问题标题】:jQuery reindex array [duplicate]jQuery重新索引数组[重复]
【发布时间】:2021-12-22 03:59:14
【问题描述】:

我有这个 javascript / jQuery 代码:

var json = [
    {
        id: 0,
        text: 'enhancement'
    },
    {
        id: 1,
        text: 'bug'
    },
    {
        id: 3,
        text: 'invalid'
    },
    {
        id: 4,
        text: 'wontfix'
    }
];



delete json[2]
console.log(json)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

此代码删除数组键 2。 但在那之后我需要一个重新索引,以便我可以访问其他 3 个值,例如:

json[0]
json[1]
json[2]

我怎样才能意识到这一点?

【问题讨论】:

  • 你试过了吗?
  • 你可以试试json.splice(2,1);
  • json.filter(j => true)

标签: javascript jquery arrays


【解决方案1】:

使用splice 代替delete,如下所示(W3schools splice):

json.splice(target_index,1);

请阅读Mozila page about the splice method了解更多信息。

【讨论】:

  • @Skully 使用 splice 后,OP 可以使用json[0] - > json[2] 并获得预期结果
【解决方案2】:

如果你不想改变值,你可以简单地过滤数组

json.filter((i, idx) => idx !== 2)

【讨论】:

    【解决方案3】:

    您只需使用即可重新索引

    json.filter(function(){return true;})
    

    这是一个工作演示。

    <!DOCTYPE html>
    <html>
    <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script>
    $(document).ready(function(){
      $("#delete").click(function(){
       var json = [
        {
            id: 0,
            text: 'enhancement'
        },
        {
            id: 1,
            text: 'bug'
        },
        {
            id: 3,
            text: 'invalid'
        },
        {
            id: 4,
            text: 'wontfix'
        }
    ];
    
    
    
    delete json[2]
    
    
    console.log(json.filter(function(){return true;}))
      });
    });
    </script>
    </head>
    <body>
     <button id="delete">delete</button>
    </body>
    </html>

    【讨论】:

      【解决方案4】:

      Splice 方法从数组中删除元素,并在必要时在其位置插入新元素,并返回已删除的元素。

      splice(start: number, deleteCount?: number)

      json.splice(2, 1);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-05-18
        • 2012-12-21
        • 2017-08-03
        • 2011-11-25
        • 2017-09-13
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多