[英]Determining whether an input number is negative or positive in javascript
如果给定一个javascript,该javascript从用户输入了一个数字作为输入,并确定该数字是负数还是正数,那么在什么情况下会抛出异常?
在特殊情况下,您应该抛出异常。 如果您接受数字输入(正数或负数),则不符合条件的内容(例如字符串或对象)应视为例外。
例:
// Assume the variable 'input' contains the value given by user...
if(typeof input != "number") {
throw "Input is not number!"
}
else {
// ... handle input normally here
}
答案取决于代码。
一个明显的功能是:
function isPosOrNeg(x) {
return x < 0? 'negative' : 'positive';
}
很难看到抛出异常。 如果x
是无法解析的引用,可能会有一个,但不是(它是一个形式参数,实际上是一个声明的变量)。
<运算符使用抽象的关系比较算法 ,该算法不会引发错误,但是根据提供的值可能会返回undefined
的值。
我根本不会抛出错误,因为undefined
是调用者可以处理的完全合理的响应。
如果要测试参数,则可能:
function isPosOrNeg(x) {
if ( isNaN(Number(x))) {
// throw an error
}
return x < 0? 'negative' : 'positive';
}
因此isPosOrNeg('foo')
会引发错误,而isPosOrNeg('5')
不会。
您可以尝试以下方法:
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';
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.