- 이차원배열
- Date
- Math
- dom
1) 이차원 배열
let arr = [
[10, 20, 30],
[40, 50, 60]
]
// arr = [[10, 20, 30], [40, 50, 60]]
위와 같은 배열을 이차원 배열이라 한다.
let a = [10, 20, 30]
let b = [40, 50, 60]
let arr1 = [a, b]
console.log(arr1);
[ [ 10, 20, 30 ], [ 40, 50, 60 ] ]
배열 두 개를 합쳐 만들 수도 있다.
console.log(arr[0][0]);
console.log(arr[0][1]);
console.log(arr[0][2]);
console.log(arr[1][0]);
10
20
30
40
첫 번째 대괄호는 행을 의미하고 두 번째 대괄호는 열을 의미한다.
따라서 arr[0][0]은 arr배열의 0번째 행 0번째 열인 10을 의미한다.
console.log(arr.length); // arr 행 length
console.log(arr[1].length); // 1번 행의 열 length
2
3
배열 자체에 length를 하면 행의 개수인 2가 출력이 되고, 배열의 1번째 행에 length를 하면 열의 개수인 3이 출력이 된다.
for(let i=0; i<arr.length; i++){
for(let j=0; j<arr[i].length; j++){
console.log(arr[i][j]);
}
}
10
20
30
40
50
60
행을 반복하는 첫번째 for문과 열을 반복하는 두 번째 for문을 이용해 이차원배열의 모든 요소를 출력해 보았다.
let sum=0;
for (let z=0; z<arr.length; z++){
for (let a=0; a<arr[z].length; a++){
sum+= arr[z][a];
}
}
----------------------------------------------
let sum1=0;
for(let x of arr){
for(let y of x)
sum1+=y;
}
----------------------------------------------
console.log(sum);
210
for문을 이용한 모든 요소들의 합 구하기. sum과 sum1은 같은 결과를 나타낸다.
2) Date
Date는 현재 날짜와 시간을 알려준다.
let now = new Date();
console.log(now);
2023-04-11T04:10:46.254Z
let now = new Date();
let y = now.getFullYear();
let m = now.getMonth()+1;
let d = now.getDate();
let dd = now.getDay();
switch(now.getDay()){
case 0 : dd = '일'; break;
case 1 : dd = '월'; break;
case 2 : dd = '화'; break;
case 3 : dd = '수'; break;
case 4 : dd = '목'; break;
case 5 : dd = '금'; break;
case 6 : dd = '토'; break;
}
let arr = ['일','월','화','수','목','금','토'];
let day =arr[now.getDay()];
console.log(`오늘은 ${y}년 ${m}월 ${d}일 ${day}요일`);
오늘은 2023년 4월 11일 화요일
Date에 있는 값중 년, 월, 일, 시, 분, 초를 따로 추출할 수 있다.
월의 경우 0월부터 시작하기 때문에 +1을 해주어야 현재 월이 정확하게 출력된다.
요일은 0부터 6까지 각각 일~토를 의미한다. 따라서 switch ~ case를 사용해 맞는 요일을 한글로 표시되게 해 보았다.
let now = new Date();
let h = now.getHours();
let m = now.getMinutes();
let s = now.getSeconds();
console.log(`${h}시 ${m}분 ${s}초`)
18시 40분 10초
시간의 경우 위와같이 뽑아낼 수 있다.
let h = now.getHours();
let ba ="";
if(h>0 && h<12) {
ba = "오전";
} else {
ba = "오후";
h = h - 12;
}
let hhh = String(h).padStart(2,0);
console.log(`지금은 ${ba} ${hhh}시 ${m}분 ${s}초`)
지금은 오후 06시 2분 45초
if문으로 시간을 24시간으로 표시하고 String을 통해 문자로 바꾼 뒤 남은 자리를 0으로 채우는 padStart를 사용해 06시로 만들어 보았다. 분과 초로 같은 방법으로 구현할 수 있다.
3) Math
Math는 숫자를 여러가지 방법으로 반환하는 내장 객체이다.
주로 사용하는 것은 아래와 같다.
.random() : 0~1 사이 실수, 0과 1은 포함되지 않음
.ceil() : 소수점 올림
.round() : 소수점 반올림
.floor() : 소수점 버림
.max() : 최댓값
.min() : 최솟값
.abs() : 절댓값
let r1 = Math.random();
console.log(r1);
// 0.XXX ~ 0.9XX
r1 = Math.random()*10;
console.log(r1);
// 0.XXX ~ 9.XXX
r1 = Math.random()+5;
console.log(r1);
// 5.XXX ~ 5.XXX
r1 = Math.abs(-2)
console.log(r1);
// 절대값
r1 = Math.ceil(5.84);
console.log(r1);
r1 = Math.floor(5.84);
console.log(r1);
r1 = Math.round(5.84);
console.log(r1);
r1 = Math.max(10,40,20,50);
console.log(r1);
r1 = Math.min(10,40,20,50);
console.log(r1);
0.8504374077773336
2.0547403656926555
5.417901936839142
2
6
5
6
50
10
random을 사용해 무작위 색을 만들어 보았다.
let x = [0,1,2,3,4,5,6,7,8,9,'A','B','C','D','E','F'];
let color ='';
for(let i=0; i<6; i++){
color+=x[Math.floor(Math.random()*x.length)];
}
console.log(`#${color}`);
// 출력값은 하나이다
#2F2F9C
#CD5744
#D4BB3D
#B13379
Math.raddom()에 x배열의 요소수만큼 곱하게 되면 0.XXX ~ 0.9XX에서 0.XXX ~ 15.9XX 사이 숫자가 나오게 된다.
그 값에 Math.floor로 소수점을 버림 하면 0 ~ 15로 x 배열의 모든 인덱스 번호를 호출할 수 있다.
for문으로 총 6자리를 위해 0번부터 5번까지 실행하게 되면 누적되어 총 6자리가 완성된다.
let x1 = Math.floor(Math.random()*16).toString(16);
let x2 = Math.floor(Math.random()*16).toString(16);
let x3 = Math.floor(Math.random()*16).toString(16);
let x4 = Math.floor(Math.random()*16).toString(16);
let x5 = Math.floor(Math.random()*16).toString(16);
let x6 = Math.floor(Math.random()*16).toString(16);
console.log(`#${x1+x2+x3+x4+x5+x6}`)
0 ~ 15 숫자를 toString을 사용해 문자로 바꿈과 동시에 진수를 지정해 만들 수도 있다.
4) dom
<body>
<ul>
<li>list</li>
<li>list</li>
<li>list</li>
<li>list</li>
<li>list</li>
</ul>
<script>
'use strict';
let arr = ['사과', '포도', '딸기', '수박', '멜론']
let li = document.getElementsByTagName('li');
console.log(li);
for(let i=0; i<arr.length; i++){
li[i].innerHTML = arr[i]
}
for(let i=0; i<arr.length; i++){
li[i].style.fontSize = '30px';
li[i].style.width = '200px';
li[i].style.height = '50px';
li[i].style.marginBottom = '10px';
li[i].style.border = '1px solid black';
li[i].style.textAlign = 'center';
}
</script>
</body>
body부분에 스크립트를 사용해 html과 css 효과도 줄 수 있다.
* 오늘은 간단하게만 배워서 제대로 사용은 못 하지만 그동안 배웠던 javascript가 웹에서 어떻게 적용되는지 볼 수 있어서 앞으로 배울 내용들이 기대가 된다.