首页 > 解决方案 > 如何在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;
    }
}

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

像:

-delete -eat //检查它是否在数组中 //如果为真则删除它

如果这是一个愚蠢的问题,我很抱歉。我在网上试了,没找到。

谢谢!

标签: javascriptarraysinputsplice

解决方案


您可以将循环更改为do while循环以检查退出,而不是使用break最后的 else 检查。

然后你需要存储结果indexOf并将项目与索引拼接。

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发表声明

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');


推荐阅读