【问题标题】:Remove element from nested array从嵌套数组中删除元素
【发布时间】:2022-07-19 20:16:19
【问题描述】:

我有这些数据:

const pages = [
  [
    {id: 1}, 
    {id:2}
  ],
  [
    {id: 3}, 
    {id:4}
  ],
];

从这个具有 2 个索引作为参数的结构中删除元素的最佳和更有效的方法是什么?

例如index1 = 1index2 = 0 将删除 pages[1][0] 并且页面将是:

const pages = [
  [
    {id: 1}, 
    {id:2}
  ],
  [
    {id:4}
  ],
];

【问题讨论】:

  • 您如何定义“最佳”?指标是什么?

标签: javascript


【解决方案1】:

pages[0].pop(); // 将删除 {id : 2}

pages[0].shift(); // 将删除 {id : 1}

【讨论】:

    【解决方案2】:

    您可以使用 array.splice 从数组中删除一个项目。

    这是一个演示,其中的函数实现了您所要求的功能:

    const pages = [
      [
        {id: 1}, 
        {id:2}
      ],
      [
        {id: 3}, 
        {id:4}
      ],
    ];
    
    removeItem(1,0);
    console.log(pages);
    
    function removeItem(index1, index2){
      pages[index1].splice(index2, 1);
    }

    x, 1);

    【讨论】:

      猜你喜欢
      • 2021-12-11
      • 2019-01-25
      • 1970-01-01
      • 2013-11-22
      • 2019-09-13
      • 2021-01-20
      • 2018-08-29
      • 1970-01-01
      相关资源
      最近更新 更多