2012-09-13 30 views
-1

如果给定了一个javascript,它将用户输入的数字作为输入并确定数字是否为正数,那么在什么情况下您会抛出异常?确定输入数字在javascript中是否定或正数

+1

这看起来像功课。这里有一些可以帮助你:http://en.wikibooks.org/wiki/JavaScript/Operators#Comparison_operators – Blender

+0

你的问题不清楚。你想要做什么?正面或负面,或验证输入? – karthikr

+0

它的一个JavaScript程序,确定用户输入是否为正或负值问我什么时候会有一个时间,其中id必须抛出一个异常 –

回答

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 
} 
+0

为什么'5'<'10'会抛出错误? – RobG

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')没有。

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'; 
     } 
    } 
相关问题