【问题标题】:Bring all items back in an array after using splice() to remove them使用 splice() 删除它们后将所有项目带回数组中
【发布时间】:2019-10-03 21:34:03
【问题描述】:

我有一个字符串数组。当我单击一个按钮时,使用 splice(2, 1) 删除该数组的第二项。当我点击第二个按钮时,我想把那些被移除的项目带回来,这样数组就变成了以前的样子。我怎样才能做到这一点?如果我使用 splice 从数组中删除所有项目,然后我想将它们带回来怎么办?

    //html
    <button onclick="removeFunc()" id="removeBtn">Remove 2nd Item</button>
    <button id="addBtn">Add Removed Elements</button>

    //js
    const addBtn = document.getElementById('addBtn');
    const removeBtn = document.getElementById('removeBtn');
    var arr = ['hello', 'howdy', 'word', 'animal'];

    function removeFunc(){
            arr.splice(2, 1);
    }

现在,我想要一个可以将那些被移除的元素带回来的函数。请帮帮我!

【问题讨论】:

  • 你能告诉我怎么做吗?请。
  • splice 返回删除的项目,您可以保存它们并再次使用 splice 将它们添加回原始数组
  • 编程的一部分,学习成为一名优秀的程序员,就是使用逻辑来解决问题。尝试一些东西,看看它们是如何失败的,尝试一些不同的东西等等。如果我只是给你答案,你将被剥夺学习的机会。

标签: javascript html css


【解决方案1】:

您可以存储拼接的项目并在以后添加项目。

function showItems() {
    document.getElementById('items').innerHTML = array.join(', ');
}

function removeItems() {
    removed.push(...array.splice(1, 1));
    showItems();
}

function addItems() {
    array.push(...removed);
    removed.length = 0;
    showItems();
}

var array = ['hello', 'howdy', 'word', 'animal'],
    removed = [];
    
    showItems();
<button onclick="removeItems()" id="removeBtn">Remove 2nd Item</button>
<button onclick="addItems()" id="addBtn">Add Removed Elements</button><br>
<p id="items"></p>

【讨论】:

    【解决方案2】:

    由于 .splice() 从原始数组中删除一个项目,您可以简单地忽略 .splice() 的返回值并使用原始数组。

    例如你有这个:

     newArray = arr.splice($.inArray(itemtoRemove, arr),1);
      console.log(newArray);
    

    应该是这样的:

     arr.splice( $.inArray(itemtoRemove,arr), 1 );
      console.log(arr);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-09-06
      • 1970-01-01
      • 1970-01-01
      • 2022-09-27
      • 1970-01-01
      • 2021-04-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多