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

标签 javascript arrays input splice

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;
    }
}

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

喜欢:

-删除 -吃 //检查其是否在数组内部 //如果为 true 则将其删除

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

谢谢!

最佳答案

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

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

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

关于javascript - 如何在JS中删除存储在数组中的输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67941839/

相关文章:

javascript - 传递通过 Javascript 设置的隐藏表单元素

php - 表格中的多个 div 标签用于特定的文本框长度

javascript - Angular DI 和继承 : injecting extensions of a base service

javascript - CollectionsFS 文件未上传到服务器

javascript - 从 JSON 响应创建 Ember 对象并使用 Handlebars 显示

php - 从关联数组中提取值时遇到问题

c++ - 等待输入 C++

javascript - 将两个函数绑定(bind)到 jQuery 中的一个按钮

javascript - 在 javascript 中获取 asp 服务器元素时出错

Java:了解泛型数组的类型删除