gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 18:41:32 25 4
gpt4 key购买 nike

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com