【问题标题】:How to get the deleted array element from the array after using the .splice method使用.splice方法后如何从数组中获取删除的数组元素
【发布时间】:2021-09-02 07:24:59
【问题描述】:

我使用 splice 方法删除了一个数组元素,它就像我想要的那样工作。 现在我也需要在 splice 方法中删除的特定数组元素。我该怎么做?

【问题讨论】:

  • 请举个例子
  • splice 方法从数组中返回已删除的项目
  • 让 currentList= this.state.todoItems; currentList.splice(index, 1) this.setState({ todoItems:currentList }) 这个方法删除了特定的数组元素,并按照我想要的方式返回了数组。我还想获取单独删除的元素。我该怎么做?
  • 你想监控变化吗?比如:检测一个项目何时被移除?
  • 我是一个初学者,正在构建一个待办事项应用程序。单击删除按钮时,将删除特定条目。单击完成的按钮任务时,我希望删除特定的数组元素,以及,我希望删除的数组元素以供进一步使用。我使用 splice 方法删除了数组元素,现在我也想要删除的数组元素以供进一步使用。

标签: javascript arrays arraylist javascript-objects


【解决方案1】:

arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0];

//removes 4th index element
var x = arr.splice(4, 1);
//splice(index,no of elements)

//console:4th index:[ 5 ]
console.log(x);


console.log(arr);
//console:[1, 2, 3, 4, 6, 7, 8, 9, 0];
//not 4th element

【讨论】:

    【解决方案2】:

    splice 返回被删除的元素,你可以把它保存到一个变量中:

    const months = ["Jan", "Feb", "March", "April", "June"];
    var x = months.splice(4, 1, 'May');
    // replaces 1 element at index 4
    console.log(x);
    console.log(months);
    // expected output: Array ["June"]Array ["Jan", "Feb", "March", "April", "May"], 
    

    【讨论】:

      猜你喜欢
      • 2021-09-23
      • 2022-08-03
      • 1970-01-01
      • 1970-01-01
      • 2014-07-30
      • 2021-04-19
      • 1970-01-01
      • 2021-05-04
      • 2019-04-07
      相关资源
      最近更新 更多