admin 管理员组

文章数量: 1086866

JavaScript Math对象(方法和示例)

JavaScript数学对象 (JavaScript Math Object)

Math is an object inbuilt in the JavaScript library that has various methods we as a programmer can use for carrying out mathematical operations.

Math是JavaScript库中内置的一个对象,它具有程序员作为编程人员可用于执行数学运算的各种方法。

To work on JavaScript and use its functions without downloading the extra compiler and installing in your system follow these steps:

要使用JavaScript并使用其功能,而无需下载额外的编译器并在系统中安装,请执行以下步骤:

Open the chrome dev console to try out the examples by right-clicking on the browser → selecting inspect → selecting console or simply type f12.

通过右键单击浏览器→选择检查→选择控制台,打开chrome dev控制台以尝试示例,或者直接键入f12。

You can see various properties attached to this object by simply logging out on the console Math.

您只需在控制台Math上注销即可看到附加到该对象的各种属性。

    console.log(Math);

It also contains very precise values of some mathematical constants such as pi, Euler's number, square root of 2, etc.

它还包含一些数学常数的非常精确的值,例如pi,欧拉数,2的平方根等。

It's pretty simple to use it. Let's start by seeing some constants on the console.

使用起来非常简单。 让我们从在控制台上看到一些常量开始。

console.log(Math.PI);
console.log(Math.LOG2E);
console.log(Math.LN2);

Math.round()方法 (Math.round() method)

We can use the round() method of this object to round any number to the nearest integer.

我们可以使用此对象的round()方法将任何数字四舍五入到最接近的整数。

console.log(Math.round(5.2)); //5
console.log(Math.round(5.7)); //6
console.log(Math.round(0.1)); //0

Math.floor()方法 (Math.floor() method)

Much similar to round is floor(), which gives an integer smaller than the number passed to it.

floor()与round非常相似,它给出的整数小于传递给它的数字。

console.log(Math.floor(2.33)); //2
console.log(Math.floor(2.99)); //2
console.log(Math.floor(11.74)); //11

Math.ceil()方法 (Math.ceil() Method)

ceil() is something that does totally opposite of floor. It gives an integer greater than the number passed to it.

ceil()与地板完全相反。 它给出的整数大于传递给它的数字。

console.log(Math.ceil(43.44)); //44
console.log(Math.ceil(9.1)); //10
console.log(Math.ceil(12.8)); //13

Math.trunc()方法 (Math.trunc() Method)

If we simply want the integer part of the number and neglect the decimal, we can use trunc().

如果我们只想要数字的整数部分而忽略小数点,则可以使用trunc()

console.log(Math.trunc(5.667)); //5
console.log(Math.trunc(0.9359)); //0

Math.random()方法 (Math.random() Method)

Math.random() gives us a random number between 0 and 1. Every time the method is invoked, a new random number is generated.

Math.random()为我们提供一个介于0和1之间的随机数。每次调用该方法时,都会生成一个新的随机数。

console.log(Math.random());

Okay so now let's build a simple program to see where we can utilize Math objects in real-world scenarios. Let's say we have to generate a random number for a lottery. We have to generate a random winning ticket in a particular range. We can set the range to initially a smaller value to test our lottery app.

好的,现在让我们构建一个简单的程序,看看在实际场景中可以在哪里使用Math对象。 假设我们必须为彩票生成一个随机数。 我们必须生成一个特定范围内的随机中奖彩票。 我们可以将范围设置为最初较小的值来测试我们的彩票应用。

All you need is an index.html so go ahead and create an index.html file in any folder and copy the following started template,

您只需要一个index.html,所以继续在任何文件夹中创建一个index.html文件,然后复制以下已启动的模板,

All we have done till now is created something that looks like this:

到目前为止,我们所做的全部工作都是如下所示:

<html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><meta http-equiv="X-UA-Compatible" content="ie=edge"><title>Lottery Game</title><style>body {text-align: center;}div {border: 2px dotted black;background: wheat;height: 400px;width: 200px;display: inline-block;}h2 {padding: 10px;text-align: center;font-family: 'Courier New', Courier, monospace}</style>
</head><body><div class="main"><h2>Welcome to lottery</h2><p>Enter your lottery number</p><input type="text" name="Maximum lottery" id="lottery"><button class="btn">Check!</button></div>
</body>
<script>
</script></html>

Output

输出量

Now we simply need to capture the input value and check it against a randomly generated number. If they're both the same, the player wins the lottery otherwise he does not.

现在,我们只需要捕获输入值并对照随机生成​​的数字对其进行检查。 如果两者相同,则玩家中奖,否则他中奖。

<script>
var lotteryNo = document.querySelector('#lottery');
var btn = document.querySelector('.btn');
var range = 10;
var winningTicket = Math.floor(Math.random() * 10);btn.addEventListener('click', () => {console.log(lotteryNo.value, winningTicket);if (winningTicket == lotteryNo.value)alert('Congrats! You win the lottery');elsealert('Sorry you lost. Better luck next time!')
})</script>

That's it! Right now we're only generating lottery numbers from 1 to 10. You can increase the range to 100 or 1000 or whatever you like. This is a very basic and simple implementation of the random() method in Math object.

而已! 现在,我们只生成1到10之间的彩票号码。您可以将范围增加到100或1000,也可以随便添加。 这是Math对象中random()方法的非常简单的基本实现。

There are other methods such as pow() which calculates a to the power b, cos(), sin(), min(), max() which are quite self-explanatory.

还有其他的方法,例如POW(),其计算到电源B,COS(),SIN(),MIN(),MAX(),它们是相当不言自明的。

console.log(Math.sqrt(64)); //8
console.log(Math.min(4,7,99)); //4
console.log(Math.max(9,-11,23)); //23

A great way to implement most of the methods of the Math Object is to make your very own calculator app.

实现大多数数学对象方法的好方法是制作自己的计算器应用程序。

翻译自: .aspx

本文标签: JavaScript Math对象(方法和示例)