简体   繁体   中英

Javascript try and catch

My code is not reporting any errors no matter what I do. This is for a indexed array and I was to get an error when I prompt user to enter the list number they want to delete. It should give me an error if its not in the index or not a integer.

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



}

simple, add the below code to beginning of try block if((input -parseInt(input ))!=0) throw new Error('not integer');

it should do the trick.

I changed your function, please see if it is what you want:

var tasks = [1,2,3,4,5,6,7,8,9,10];

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

    //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 if (delTask == 0){
            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>';
        document.getElementById('output').innerHTML = delMessage; 
    } else {
        throw "The value is not number or not index of array! Try again!";
    }
    //Return false to prevent submission:
    return false;
}

try {
    deleteTask();
} catch (e) {
    console.log(e);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM