This article describes the method of obtaining the absolute value of a variable in js. Share it for your reference. The specific analysis is as follows:
In js, we directly use the abs function to find the absolute value of variables. Here we will organize some methods for obtaining the absolute value of variables in js, so that everyone can understand the usage of js' absolute value more deeply.
The absolute value in js is not very commonly used. Today I encountered it when I was writing a method, so I recorded it and learned it with everyone.
The default object in js - There is an abs function under the Math object, which is specifically used to obtain the absolute value of a number, such as:
Copy the code as follows: Math.abs(-1); //1
Math.abs(-2); //2
Of course, this function can also be used to obtain the absolute value of a variable, such as:
The code copy is as follows: var aaa=-3;
var bbb=abs(aaa); //3
example:
Copy the code as follows:<script language="javascript">
document.write("0 is absolute value:",Math.abs(0),"<br>");
document.write("1's absolute value is:",Math.abs(1),"<br>");
The absolute value of document.write("-1 is:",Math.abs(-1),"<br>");
//-->
</script>
Another way:
We know that the absolute value in mathematics is no matter decimal or integer, and of course the same is true here.
The code copy is as follows: var aaa=-3.3;
var bbb=abs(aaa); //3.3
I hope this article will be helpful to everyone's JavaScript programming.