javascript - 如何在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 //检查它是否在数组中 //如果为真则删除它
如果这是一个愚蠢的问题,我很抱歉。我在网上试了,没找到。
谢谢!
解决方案
您可以将循环更改为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');
推荐阅读
- c# - 为什么发生异常时未从 Mvc 设置 StatusCode
- python - 在python中为groupby动态选择数据框列
- java - 需要 POJO 对象才能使用 Spring Boot 自动装配以下 yml 结构
- r - 通过检测一个字符串中的任何多个字符串模式来创建一个变量
- javafx - 尝试运行 javafx 应用程序时出错
- dialogflow-es - 如何在 Web 演示的对话流中添加链接或图像作为响应
- wso2 - WSO2 复合应用程序项目在向导中不显示任何依赖项
- javascript - 如何在没有 ReactJS 的情况下使用 Shopify Polaris?
- java - Log4J 2 查找值在加载/存在之前在配置中使用
- android - 无法在手机和模拟器上播放视频 VideoView android 错误