如何在JS中删除存储在数组中的输入

问题描述

let input;
const todos = [];

while (input !== 'exit') {
    input = prompt('Type what you want to do');
    if (input === 'new') {
        input = prompt("What's your todo?");
        todos.push(input);
    } else if (input === 'list') {
        console.log(`This is your list of todos: ${todos}`);
    } else if (input === 'delete') {
        input = prompt('Which todo would you like to delete?');
        if (todos.indexOf(input) !== -1) {
            todos.splice(1,1,input);
            console.log(`You've deleted ${input}`);
        }
    } else {
        break;
    }
}

这就是我迄今为止尝试过的。 我正在开始编程,这是一个小练习的一部分,我必须根据提示要求添加一个新的待办事项,将其全部列出,然后删除。 我想要做的是:获取存储在输入变量中的输入,然后检查它是否在数组内部,如果它是肯定的,我想删除它而不是从索引而是从单词中删除

喜欢:

-删除 -吃 //检查它的内部数组 //如果为真则删除

如果这是一个愚蠢的问题,我深表歉意。我在网上试过了,没找到。

谢谢!

解决方法

您可以将循环更改为 do while 循环来检查出口,而不是最后使用 break 进行检查。

然后需要将indexOf的结果存储起来,将item与索引拼接起来。

let input;
const todos = [];

do {
  input = prompt('Type what you want to do');
  if (input === 'new') {
    input = prompt("What's your todo?");
    todos.push(input);
  } else if (input === 'list') {
    console.log(`This is your list of todos: ${todos}`);
  } else if (input === 'delete') {
    input = prompt('Which todo would you like to delete?');
    const index = todos.indexOf(input)
    if (index !== -1) {
      todos.splice(index,1);
      console.log(`You've deleted ${input}`);
    }
  }
} while (input !== 'exit');

稍微更好的方法是采用 switch statement

let input;
const todos = [];

do {
    input = prompt('Type what you want to do');
    switch (input) {
        case 'new':
            input = prompt("What's your todo?");
            todos.push(input);
            break;
        case 'list':
            console.log(`This is your list of todos: ${todos}`);
            break;
        case 'delete':
            input = prompt('Which todo would you like to delete?');
            const index = todos.indexOf(input)
            if (index !== -1) {
                todos.splice(index,1);
                console.log(`You've deleted ${input}`);
            }
    }
} while (input !== 'exit');

,

您的代码已修复如下:

input = prompt('Which todo would you like to delete?');
const index = todos.indexOf(input);
if (~index) {
  todos.splice(index,1);
  console.log(`You've deleted ${input}`);
}

您可以在相应的 MDN 文档中阅读有关 Array.prototype.splice()bitwise operator 的更多信息。

,

按照 this 正确使用 splice。

你想要的是这样的:

  todos.splice(yourIndex,1);

第一个参数是您想要操作数组的起始索引,第二个参数是计数。拼接到位,会修改数组。

,

使用 indexOf 方法找到索引,然后使用 splice 方法!

let todos = ['one','two','three'];
let index;

// Wrap the whole code in function to make it resusable
let user_input = prompt(" Enter your to-do to delete ");
index = todos.indexOf(user_input);

if (index !== -1) {
  todos = todos.splice(index,1);
  console.log("Entered to-do deleted successfully");
} else {
  alert("Entered to-do doesn't exists");
}

还请记住,作为初学者,有问题是件好事!