gpt4 book ai didi

JavaScript 尝试并捕获

转载 作者:行者123 更新时间:2023-12-03 11:32:50 25 4
gpt4 key购买 nike

无论我做什么,我的代码都不会报告任何错误。这是针对索引数组的,当我提示用户输入他们想要删除的列表编号时,我收到错误。如果它不在索引中或不是整数,它应该给我一个错误。

function deleteTask(){
'use strict';
//Prompt user
var input = prompt("what task do you want to delete?");

var delMessage = ' ';

try {
//Convert to integer
var delTask = parseInt(input);
//Validates that user input was number and is range of to do list
if ((typeof delTask == 'number') && (delTask <= tasks.length)){
if (delTask > 1){
//removes element from array
var oneDown = parseInt(delTask - 1);
tasks.splice(oneDown, 1);
}else{
tasks.splice(0,1);
}

delMessage = '<h2>To-Do</h2><ol>';
for (var i = 0, count = tasks.length; i < count; i++) {
delMessage += '<li>' + tasks[i] + '</li>';
}
delMessage += '</ol>';
output.innerHTML = delMessage;
}
//Return false to prevent submission:
return false;

}catch(ex){
console.log(ex.message);
}



}

最佳答案

简单,将以下代码添加到 try block 的开头if((input -parseInt(input ))!=0) throw new Error('非整数');

它应该可以解决问题。

关于JavaScript 尝试并捕获,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26666577/

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