为了账号安全,请及时绑定邮箱和手机立即绑定

请问这里判断数字的返回值,为什么只能是数字?

请问这里判断数字的返回值,为什么只能是数字?

依韵S1 2016-12-19 09:33:50
.p1 { background-color:#abcdef; color:green; } .p2 { background-color:#000; color:#fff; } div { margin:10px; }<input type="text" class="js-text2" value=""/> <input type="text" class="js-text3" value=""/> <input type="button" onclick="calculate('+')" value="加" /> <input type="button" onclick="calculate('-')" value="减" /> <input type="button" onclick="calculate('*')" value="乘" /> <input type="button" onclick="calculate('/')" value="除" /> <script> function calculate(a){ var num1 = $("js-text2").value; var num2 = $('js-text3').value; var isnum1 = isnumber(num1); var isnum2 = isnumber(num2); if(isnum1==2||isnum2==2){ alert("含有非法字符"); return false; }else{ if( isnum1==0 && isnum2==0 ) { if( a=='+' ) { alert(parseInt(num1)+parseInt(num2)); } else if( a=='-' ) { alert(parseInt(num1)-parseInt(num2)); } else if( a=='*' ) { alert(parseInt(num1)*parseInt(num2)); } else if( a=='/' ) { alert(parseInt(num1)/parseInt(num2)); } } } } function $(classname){ return document.getElementsByClassName(classname)[0]; } /* return 0:整数; 1:小数; 2:非法字符 */ //只能整数运算 function isnumber(a){ if(!isNaN(a)){ var array = a.split('.'); var count = array.length; if(count==1){ return 0; }else{ if(count==2){ if(parseInt(array[1])==0){ return 0; }else{ return 2; } }else{ return 2; } } }else{ return 2; } } </script>这是一个整数的加减乘除,我想问的是判断是否为整数(函数 isnumber)返回的值,为什么只能是数字。我尝试将 返回的数字改成字母就会报错
查看完整描述

2 回答

?
这是一首

TA贡献55条经验 获得超6个赞

function isNum(s) {
 //var regu = "^([0-9]*)$";
 var regu = "^([0-9]*[.0-9])$"; // 小数测试
 var re = new RegExp(regu);
 if (s.search(re) != -1)
  return true;
 else
  return false;
}

试试这个

查看完整回答
反对 回复 2016-12-19
  • 依韵S1
    依韵S1
    兄弟我只想知道为啥我上面那段只能是数字,,
  • 依韵S1
    依韵S1
    正则我还没接触到。就算复制了你的代码我也不懂什么意思呢。。
  • 2 回答
  • 0 关注
  • 1264 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信