Javascript给出undefined而不是ex.message

时间:2016-10-29 13:48:40

标签: javascript

以下代码有效,只有当我在prompt()中输入字母时,才会收到未定义的消息,而不是ex.message中的WrongValue catch(ex)。我尝试了很多变化,但我仍然不知道出了什么问题。我该如何正确地做到这一点?

var myList = ["Oranges", "Apples", "Pineapples", "Bananas"];


var getFruit = function(index) {
  if (index > myList.length || index < 0) {
    throw new RangeError("The number you gave doesn't exist in the list, the number must be 0 <= # <= " + myList.length);
  } else {
    return myList[index];
  }

  if (isNaN(index)) {
    throw new WrongValue("Give a number please");
  } else {
    return myList[index];
  }
}

try {
  getFruit(prompt("Which fruit are you looking for"));
} catch (ex) {
  if (ex instanceof RangeError) {
    console.log(ex.message);
  }

  if (ex instanceof WrongValue) {
    console.log(ex.message);
  }
}

2 个答案:

答案 0 :(得分:0)

检查isNaN FIRST ...将getFruit更改为以下

var getFruit = function(index) {
    if(isNaN(index)) {
        throw new WrongValue("Give a number please");
    else if(index > myList.length || index < 0) {
        throw new RangeError("The number you gave doesn't exist in the list, the number must be 0 <= # <= " + myList.length);
    } else {
        return myList[index];
    }

}

答案 1 :(得分:0)

现在写的总是你的条件之一将被检查,因为他们returnthrow两者都阻止代码继续下一条指令,所以试着将两者结合起来条件为1并首先检查isNaN(),如:

var getFruit = function(index) {
  if (isNaN(index)) {
    throw new WrongValue("Give a number please");
  } else if (index > myList.length || index < 0) {
    throw new RangeError("The number you gave doesn't exist in the list, the number must be 0 <= # <= " + myList.length);
  } else {
    return myList[index];
  }
}

希望这有帮助。