[英]How do I continue checking whether a value is correct in javascript?
I have a javascript code that asks a user to input an entry, prints out a list of entries, and deletes.我有一个 javascript 代码,要求用户输入一个条目,打印出条目列表,然后删除。 The problem is that when the user inputs delete and than enters an invalid number the code says to enter a correct index but if the user inputs still an incorrect index value based on my specifications the code stops checking whether it passes the test.问题是,当用户输入删除而不是输入无效数字时,代码会说要输入正确的索引,但是如果用户根据我的规范输入的索引值仍然不正确,代码将停止检查它是否通过测试。 I need the code to constantly check if the input is valid for index even after the user keeps putting a wrong index number.我需要代码来不断检查输入是否对索引有效,即使在用户不断输入错误的索引号之后也是如此。 The code must not exit unless the correct index value is entered.除非输入正确的索引值,否则代码不得退出。 Here is the code这是代码
let action = prompt("What would you like to do");
const todo = []
let count=0
let tracker=0
let char = 'x'
while (action !== 'quit' && action !== 'q'){
if (action === 'new'){
action = prompt("What would you like to add");
todo.push(action)
tracker=0;
}
else if (action === 'list'){
console.log(char.repeat(10))
for (let elements of todo){
console.log(`${tracker}: ${elements}`)
tracker++
}
console.log(char.repeat(10))
action = prompt("What would you like to do");
}
else if (action === 'delete'){
let index = parseInt(prompt("Enter the index of the todo you would like to delete"))
if (index<todo.length && index >-1 && index!==null){
todo.splice(index,1)
tracker=0;
}
else{
let index = parseInt(prompt("Enter a correct index"))
}
action = prompt("What would you like to do");
}
else
{
action = prompt("What would you like to do");
}
}
console.log("Ok quit the app")
Replace this part:替换这部分:
let index = parseInt(prompt("Enter the index of the todo you would like to delete"))
if (index<todo.length && index >-1 && index!==null){
todo.splice(index,1)
tracker=0;
}
else{
let index = parseInt(prompt("Enter a correct index"))
}
With this -- using a loop:有了这个——使用循环:
let index = parseInt(prompt("Enter the index of the todo you would like to delete"));
while (!(index < todo.length && index >= 0)) {
index = parseInt(prompt("Enter a correct index"));
}
todo.splice(index, 1);
tracker = 0;
Note: parseInt
will never return null
, so no need to check for that.注意: parseInt
永远不会返回null
,因此无需检查。 Instead, it could return NaN
.相反,它可以返回NaN
。 But as any comparison with NaN
will evaluate to false
, the negation of that (using !
) will evaluate to true
.但是由于与NaN
的任何比较都将评估为false
,因此对它的否定(使用!
)将评估为true
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.