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

How to delete an input stored in array in 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;
    }
}

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

喜欢:

-删除 -吃 //检查其内部数组 //如果为真,将其从

中删除

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

谢谢!

您的代码已修复如下:

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() and the bitwise operator 的更多信息。

遵循 this 正确使用 splice。

你想要的是这样的:

  todos.splice(yourIndex,1);

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

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

然后需要存储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');

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

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

还记得作为初学者有问题是好的!