\(@^0^@)/

[JS] Math.func + JS Array Methods ( join, split ) 본문

TIL

[JS] Math.func + JS Array Methods ( join, split )

minjuuu 2021. 8. 28. 12:53
728x90

무작위 숫자를 만드는 함수는 Math.random()
(0 이상 1 미만의 수를 무작위로 생성)

만약, 1에서 9까지의 숫자가 필요할 경우
Math.random()에 9를 곱한 후 1을 더하면 1 이상 10 미만의 수가 만들어짐.

숫자를 자연수로 만들려면 내림, 올림, 반올림을 해야 함.
숫자의 내림은 Math.floor() 올림은 Math.ceil(), 반올림은 Math.round() 로 할 수 있음.

// 0 <= x < 1
Math.random()

// 0 <= x < 9
Math.random() * 9

// 1 <= x < 10
Math.random() * 9 + 1

// x = {1, 2, 3, 4, 5, 6, 7, 8, 9}
Math.floor(Math.random() * 9 + 1)

랜덤함수를 만들고, 0-9까지의 범위
자연수로 만들어 내림(floor)
숫자의 반올림(round), 올림(ceil)

 

배열을 문자열로 바꾸는 join 함수, 문자열을 분리하여 배열을 생성하는 split 함수


 참고 : ZeroCho Tv - ES2021 자바스크립트 강좌

※ MDN (math) : https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Math

※ MDN (array)  : https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array

※ 더 알아보기 : http://tcpschool.com/javascript/js_standard_arrayMethod

728x90