PL
JavaScript - Math.abs() - przykład metody z dokumentacją
2 points
Funkcja Math.abs()
zwraca wartość absolutną dla podanej liczby.
Wartość bezwzględna liczby x, oznaczona | x |, jest nieujemną wartością x - bez względu na jej znak.
Popularne przykłady użycia:
xxxxxxxxxx
1
console.log( Math.abs(2) ); // 2
2
console.log( Math.abs(-2) ); // 2
3
4
console.log( Math.abs(2.54) ); // 2.54
5
console.log( Math.abs(-2.54) ); // 2.54
6
7
console.log( Math.abs(0) ); // 0
8
console.log( Math.abs('-2') ); // 2
9
console.log( Math.abs('2') ); // 2
Inne przykłady użycia:
xxxxxxxxxx
1
console.log( Math.abs(3 + 5) ); // 8
2
console.log( Math.abs(3 - 5) ); // 2
3
4
console.log( Math.abs('') ); // 0
5
console.log( Math.abs('abc') ); // NaN
6
console.log( Math.abs(null) ); // 0
7
8
console.log( Math.abs([]) ); // 0
9
console.log( Math.abs([0]) ); // 0
10
console.log( Math.abs([2]) ); // 2
Składnia | Math.abs(number) |
Parametry | number - liczba całkowita lub liczba zmiennoprzecinkowa (typ prosty). |
Wynik | Wartość bezwzględna liczby (typ prosty). |
Opis |
|
xxxxxxxxxx
1
function abs(x) {
2
if (x < 0) {
3
return -x;
4
}
5
return x;
6
}
7
8
console.log(abs(2)); // 2
9
console.log(abs(-2)); // 2
10
console.log(abs(0)); // 2
Uwaga: istnieje kilka sposobów, aby zmienić znak na przeciwny, jeśli warunek (x <0)
jest spełniony:
x = -x
x *= -1
x = ~x + 1
Przeczytaj ten artykuł, aby dowiedzieć się o najlepszym sposobie negowania wartości.
xxxxxxxxxx
1
2
<html>
3
<head>
4
<style> #canvas { border: 1px solid black; } </style>
5
</head>
6
<body>
7
<canvas id="canvas" width="400" height="50"></canvas>
8
<script>
9
10
var canvas = document.querySelector('#canvas');
11
var context = canvas.getContext('2d');
12
13
// zakres rysowanego wykresu sinus
14
var x1 = -2 * Math.PI; // -360 degress
15
var x2 = +2 * Math.PI; // +360 degress
16
var y1 = -0.1;
17
var y2 = +1.1;
18
19
var dx = 0.01;
20
21
var xRange = x2 - x1;
22
var yRange = y2 - y1;
23
24
function calculatePoint(x) {
25
var y = Math.abs(Math.sin(x)); // y=|sin(x)|
26
27
// wykres zostanie odwrócony w poziomie
28
// z powodu odwróconych pikseli na ekranie
29
30
var nx = (x - x1) / xRange; // znormalizowany x
31
var ny = 1.0 - (y - y1) / yRange; // znormalizowany y
32
33
var point = {
34
x: nx * canvas.width,
35
y: ny * canvas.height
36
};
37
38
return point;
39
}
40
41
console.log('x range: <' + x1 + '; ' + x2 + '> // stopnie w radianach');
42
console.log('y range: <' + y1 + '; ' + y2 + '>');
43
44
var point = calculatePoint(x1);
45
46
context.beginPath();
47
context.moveTo(point.x, point.y);
48
49
for (var x = x1 + dx; x < x2; x += dx) {
50
point = calculatePoint(x);
51
context.lineTo(point.x, point.y);
52
}
53
54
point = calculatePoint(x2);
55
context.lineTo(point.x, point.y);
56
context.stroke();
57
58
</script>
59
</body>
60
</html>