简体   繁体   中英

Determining whether an input number is negative or positive in javascript

如果给定一个javascript,该javascript从用户输入了一个数字作为输入,并确定该数字是负数还是正数,那么在什么情况下会抛出异常?

You should throw exceptions in exceptional situations. If you're accepting input of a number (either positive or negative), then something that doesn't fit the criteria, like say a string or an object, should be considered exceptional.

Example:

// Assume the variable 'input' contains the value given by user...
if(typeof input != "number") {
    throw "Input is not number!"
}
else {
    // ... handle input normally here
}

The answer depends on the code.

An obvious function is:

function isPosOrNeg(x) {
  return x < 0? 'negative' : 'positive';
}

it's very difficult to see that throwing an exception. There might be one if x is an unresolvable reference, but it isn't (it's a formal parameter so effectively a declared variable).

The < operator uses the abstract relational comparison algorithm , which doesn't throw errors, though it might return undefined depending on the values provided.

I wouldn't throw an error at all, since undefined is a perfectly reasonable response that the caller can deal with.

If you want to test the parameters, then perhaps:

function isPosOrNeg(x) {

  if ( isNaN(Number(x))) {
    // throw an error
  }

  return x < 0? 'negative' : 'positive';
}

so that isPosOrNeg('foo') throws an error but isPosOrNeg('5') does not.

You can try this:

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

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