投稿数 585
公開から 2940

JavaScript計算Mathまとめ


Categories: javascript

いきさつ

Mathとかってよく出ててるけどあんまりよくわかってないご。

Mathの例

Math.min(Math.max(val, min), max);

Mathオブジェクトとは?

JavaScript Mathオブジェクトを使用すると、数値に対して数学的なタスクを実行できます。

いろいろなプロパティがあるのでざっくり見ていきましょう

Math.round(x)

xの値を最も近い整数に丸めた値を返します。

Math.round(4.7); // returns 5

Math.pow(x, y)

xの値をyの累乗で返します。

Math.pow(8, 2); // returns 64

Math.sqrt(x)

xの平方根を返します。

Math.sqrt(64); // returns 8

Math.abs(x)

xの絶対(正)値を返します。

Math.abs(-4.7); // returns 4.7

Math.ceil(x)

xの値を最も近い整数に切り上げて返します

Math.ceil(4.4); // returns 5

Math.floor(x)

xの値を最も近い整数に切り捨てて返します。

Math.floor(4.7); // returns 4

Math.sin(x)

Math.sin(x)は、角度x(ラジアン単位)のサイン(-1〜1の値)を返します。 ラジアンではなく度を使用する場合は、度をラジアンに変換する必要があります。 ラジアン単位の角度=度単位の角度x PI / 180

…ちょっとこれは数学やったことない僕にはわからなかったです…汗

Math.sin((90 * Math.PI) / 180); // returns 1 (the sine of 90 degrees)

Math.min() and Math.max()

引数のリストで最小値または最大値を見つけるために使用できます。

Math.min(0, 150, 30, 20, -8, -200); // returns -200

Math.random()

0(包括的)と1(排他的)の間の乱数を返します

Math.random(); // returns a random number

Math Properties

JavaScriptは、Mathオブジェクトを使用してアクセスできる8つの数学定数を提供します。

Math.E; // returns Euler's number
Math.PI; // returns PI
Math.SQRT2; // returns the square root of 2
Math.SQRT1_2; // returns the square root of 1/2
Math.LN2; // returns the natural logarithm of 2
Math.LN10; // returns the natural logarithm of 10
Math.LOG2E; // returns base 2 logarithm of E
Math.LOG10E; // returns base 10 logarithm of E

実例

こんなかんじでUtil関数とか作ると良さそう。

function minMax(val, min, max) {
  return Math.min(Math.max(val, min), max);
}

参考

https://www.w3schools.com/js/js\_math.asp