我如何区分数字和特殊字符?

时间:2017-01-28 07:36:07

标签: javascript

value = "+"
isNaN(value)

条件为假

value > 0

条件成真

value ="200"
isNaN(value)

条件为假

value > 0

条件成真

这就是value > 0显示true的情况,我想区分+ - / *等数字0,200,5等。

是否可以在Javascript中执行此操作?

1 个答案:

答案 0 :(得分:2)

似乎正在工作,因为你想要/期待。



value = "+";
// is true as "+" isn't a number
console.log(isNaN(value));
// is false because "+" isn't greater than 0
console.log(value > 0);

value = "200";
// is false, because value is a number
console.log(isNaN(value));
// is true because "200" is greater than 0
console.log(value > 0);




但是,您可以实现isNumeric函数



function isNumeric(n) {
  return !isNaN(parseFloat(n)) && isFinite(n);
}

value = "+";
// is false because "+" isn't numeric
console.log(isNumeric(value));
// is false because "+" isn't greater than 0
console.log(value > 0);

value = "200";
// is true, because value is numeric
console.log(isNumeric(value));
// is true, because "200" is greater than 0
console.log(value > 0);




或者您可以使用typeof



value = "+";
// is false as "+" is a string
console.log(typeof(value) === "number");
// is false because "+" isn't greater than 0
console.log(value > 0);

value = "200";
// is false, because value is a string not a number
console.log(typeof(value) === "number");
// is true because "200" is greater than 0, this auto converts to 200
console.log(value > 0);




带有数字和符号的正则表达式



function symbolCompare(value) {
  var results = /(\+|\-)(\d+)/.exec(value);
  if(results) {
    return results[2];
  }
  
  return false;
}

value = "+200";
// is false because 200 is a number
console.log(isNaN(symbolCompare(value)));
// is true because 200 > 0
console.log(symbolCompare(value) > 0);

value = "-200";
// is false because 200 is a number
console.log(isNaN(symbolCompare(value)));
// is true because 200 > 0
console.log(symbolCompare(value) > 0);