Home >Web Front-end >JS Tutorial >Analysis of JavaScript's Judgment and Processing of Numbers
This article mainly introduces JavaScript's method of judging and processing numbers. It analyzes common methods of judging numbers and techniques for number processing in JavaScript with examples. It has certain reference value. Friends who need it can refer to it. The specific analysis is as follows :
The polymorphic attributes of Javascript are very cool. A var does not need to remember so many strange variables. However, sometimes you will be confused, why, I am obviously adding two numbers, But what if the results are added as strings? This is the disadvantage of Javascript's var. Unlike php, it uses a . to indicate that this is a string connection. This is where you need parseFloat to explicitly indicate that this var is a number. You need to use isNaN to determine whether this is a number. When isNaN (a judged var), if the result is true, then it is not a number. If the result is false, then it is a number. Note here.
The following is such a program. If you input two numbers, you can add them normally. If any of the input numbers is not a number, then a prompt will pop up. If the two input numbers are numbers, the result will pop up. It’s worth it. Note that in Javascript, 00000.22 will also be considered a number, which is 0.22
This program is written like this. Also note that in addition to judging whether num1 or num2 is While counting, you must also prevent the user from clicking the cancel button! :
<html> <head> <meta http-equiv="content-type" content="text/html;charset=utf-8"/> </head> <body> </body> </html> <script> var num1=window.prompt("请输入一个数"); var num2=window.prompt("请输入第二个数"); if(isNaN(num1)||isNaN(num2)||!num1||!num2) alert("任意一个不是数!"); else{ var res=parseFloat(num1)+parseFloat(num2); alert("两数相加的结果是:"+res); } document.write("程序已经运行完毕,大家散了吧!"); </script>
window.prompt can pop up an input box. Although it is rarely used in today’s web pages and is almost invisible, then follow the above process and finally use document.write. Output information on the web page in an overlay manner. The so-called output information in an overlay manner means that no matter what content is on the web page, it will be overwritten by the content in document.write. This method is rarely used now.
The above is the entire content of this chapter. For more related tutorials, please visit JavaScript Video Tutorial!