Home >Web Front-end >JS Tutorial >What is the usage of random in javascript

What is the usage of random in javascript

醉折花枝作酒筹
醉折花枝作酒筹Original
2021-06-10 11:49:144791browse

In javascript, the usage of random is "Math.random()". The "random()" method can return a random number between 0 and 1. The value returned by this method can be 0, but it cannot be 1.

What is the usage of random in javascript

The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.

Get a random integer between A and B:

Math.floor(Math.random()*B)+A

Get a random Boolean value:

(Math.random()>0.495): 50% There is a probability of returning true and a 50% probability of returning false

Another example is (Math.random()>0.7): There is a 70% probability of returning true and a 30% probability of returning fasle

Remember Math .random() never returns 1. At the same time, because we are using Math.floor() to round down, the final result we obtain cannot be 1. This ensures that we get a number between 0 and 1.

Example:

<html>
<body>

<script type="text/javascript">

document.write(Math.random())

</script>

</body>
</html>

Result:

0.5528221991387223

[Recommended learning: javascript advanced tutorial]

The above is the detailed content of What is the usage of random in javascript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn