简体   繁体   English

使用 JavaScript splice/indexOf 从数组中删除项目

[英]Remove an Item From an Array with JavaScript splice/indexOf

I am trying to add another button that will remove tasks from the list, and allow the user to remove any of them.我正在尝试添加另一个按钮,该按钮将从列表中删除任务,并允许用户删除其中的任何一个。 I am trying to use splice with indexOf but it's not working so far.我正在尝试将 splice 与 indexOf 一起使用,但到目前为止还没有工作。 Here is the code.这是代码。 Thanks for the help.谢谢您的帮助。

// tasks.js #2
// This script manages a to-do list.

// Need a global variable:
var tasks = [];

// Function called when the form is submitted.
// Function adds a task to the global array.
function addTask() {
'use strict';

// Get the task:
var task = document.getElementById('task');

// Reference to where the output goes:
var output = document.getElementById('output');

// For the output:
var message = '';

if (task.value) {

    // Add the item to the array:
    tasks.push(task.value);

    // Update the page:
    message = '<h2>To-Do</h2><ol>';
    for (var i = 0, count = tasks.length; i < count; i++) {
        message += '<li>' + tasks[i] + '</li>';
    }
    message += '</ol>';
    output.innerHTML = message;

} // End of task.value IF.

// Return false to prevent submission:
return false;

} // End of addTask() function.

function deleteTask() {
var inputTask = document.getElementById('task');
var taskLength = inputTask.length;

var i = array.indexOf("inputTask");
if (i != -1) {
    array.splice(i, taskLength);
}

}
// Initial setup:
function init() {
    'use strict';
    //document.getElementById('theForm').onsubmit = addTask;

    var elem1 = document.getElementById("submit");
    elem1.addEventListener("click", addTask, false);

   var elem2 = document.getElementById("delete");
    elem2.addEventListener("click", deleteTask, false);
} // End of init() function.
window.onload = init;
const array = ["a", "b", "c", "d"];

const index = array.indexOf("c");

if (index > -1) {
  array.splice(index, 1);
}

console.log(array); // ["a","b","d"]

If you want to build deleteTask function the same way as addTask built, you need to implement the following algorithm:如果要像构建addTask一样构建deleteTask函数,则需要实现以下算法:

1) find the task element in DOM and get its value
2) check whether or not the value is in the `tasks` array
3) if it's there, remove it

Here's one approach to do this:这是执行此操作的一种方法:

function deleteTask() {
  // 1
  var taskEl    = document.getElementById('task');
  // 2
  var taskIndex = tasks.indexOf(taskEl.value);
  if (taskIndex !== -1) {
    // 3
    tasks.splice(taskIndex, 1);
  }
  return false;
}

In practice, though, I'd probably go a bit different way.不过,在实践中,我可能会采取一些不同的方式。 Currently addTask and deleteTask have the same code for collecting the value of this task, but it's preventable - just extract the code that retrieves the value into a separate action (named something like getCurrentTask ) and make these methods work with task param instead.目前addTaskdeleteTask具有用于收集此任务值的相同代码,但它是可以预防的 - 只需将检索值的代码提取到单独的操作中(命名为getCurrentTask ),并使这些方法与task参数一起task

You store a reference to an element #inputTask in the inputTask variable but then try to get the index of a string "inputTask" in an array array (which does not exsist, as mentionned by @Frits in the comments).您在inputTask变量中存储对元素 #inputTask 的引用,然后尝试获取数组array字符串"inputTask"的索引(它不存在,正如@Frits 在评论中提到的那样)。

Then you try to splice the array with the index and the length of inputTask which has no length because it's an element, and if it was a string, why use its length to splice ?然后你尝试用inputTask的索引和长度拼接数组,它没有长度,因为它是一个元素,如果它是一个字符串,为什么要用它的长度来拼接?

Splice removes (and adds) elements : the first argument is the index of the first element you want to remove, the second agrument is the number of elements you want to remove from the array. Splice 删除(并添加)元素:第一个参数是要删除的第一个元素的索引,第二个参数是要从数组中删除的元素数。 So if you want to remove one element, it should look like array.splice(index, 1)所以如果你想删除一个元素,它应该看起来像array.splice(index, 1)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM