如果给出一个javascript从用户输入一个数字并确定该数字是负数还是正数,那么在什么情况下你会抛出异常?
答案 0 :(得分:2)
您应该在例外情况下抛出异常。如果你接受一个数字(正面或负面)的输入,那么一些不符合标准的东西,比如说一个字符串或一个对象,应该被视为例外。
示例:强>
// Assume the variable 'input' contains the value given by user...
if(typeof input != "number") {
throw "Input is not number!"
}
else {
// ... handle input normally here
}
答案 1 :(得分:0)
答案取决于代码。
一个显而易见的功能是:
function isPosOrNeg(x) {
return x < 0? 'negative' : 'positive';
}
很难看到抛出异常。如果x
是一个无法解析的引用,可能会有一个,但它不是(它是一个形式参数,所以实际上是一个声明的变量)。
<运算符使用abstract relational comparison algorithm,它不会抛出错误,但可能会返回undefined
,具体取决于提供的值。
我根本不会抛出错误,因为undefined
是一个非常合理的响应,调用者可以处理。
如果你想测试参数,那么可能:
function isPosOrNeg(x) {
if ( isNaN(Number(x))) {
// throw an error
}
return x < 0? 'negative' : 'positive';
}
以便isPosOrNeg('foo')
抛出错误但isPosOrNeg('5')
没有。
答案 2 :(得分:0)
你可以试试这个:
var inp="your input value";
if(isNaN(inp)){
return "Not a number";
} else {
if( inp > 0 ) {
return 'positive number';
} else if( inp < 0 ) {
return 'negative number';
} else {
return 'number is zero';
}
}