웹프로그래밍/HTML CSS JavaScript

[JavaScript] 배열 / 함수 / confirm()

아잠만_ 2024. 5. 7. 14:21

배열

자바스크립트의 배열 크기는 동적이다 

const arr = []
const arr = new Array()

 

배열을 출력하는 법 : 배열(arr)일 경우

  1. 값을 직접 찍는 방법
    document.getElementById(res).innerHTML=arr;
  2. for문을 활용하여 문자열에 저장
    for(let i=0; i<arr.length; i++){
    str+=arr[i]+" ";
    }
  3. forEach(function(문자열, 순서) {} )
    arr.forEach(function(ar, index){
    str += ` ${index} 번째 : ${ar} <br>`;
    })
  4. for(x in arr){
    str += arr[x] + " ";
    }
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="../CSS/public.css"> 
<meta charset="UTF-8">
<title>Insert title here</title>
<script>
const proc1 = () => {
	// 방법1
	const arr = ["사과","복숭아","바나나","파인애플","딸기"];
	
	// 방법 1-1
// 	const arr = [];
// 	arr[0] ="사과";
// 	arr[1] = "복숭아";
	
	// 방법2
// 	const arr = new Array("사과","복숭아","바나나","파인애플","딸기");
	
	// 방법 2-1
// 	const arr = new Array(2);
// 	arr[0] ="사과";
// 	arr[1] ="복숭아";
// 	arr[2] ="바나나";	// 동적으로 크기가 증가
	
	printArr('result1',arr);
}

const printArr = (res, arr) => {
// 	document.getElementById(res).innerHTML=arr;	// 값을 직접 찍을 수 있음
	
	let str = "";
// 	for(let i=0; i<arr.length; i++){
// 		str+=arr[i]+" ";
// 	}
	
	arr.forEach(function(ar, index){
// 		str += ar+" ";
		str += ` ${index} 번째 : ${ar} <br>`;
	})

	document.getElementById(res).innerHTML=str;
} 
</script>
</head>
<body>

	<div class="box">
		<h3>const arr = []<br>
		const arr = new Array()</h3>
		<input type="button" value="확인" onclick="proc1()"> <br> <br>

		<div id="result1"></div>
	</div>
</body>
</html>

함수

  1. 함수 선언식
    function 함수이름(매개변수){ }
  2. 함수 표현식 - 익명함수 - 변수에 대입
    const 함수이름 = (매개변수) => { }

계산기 예제

<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="../CSS/public.css"> 
<meta charset="UTF-8">
<title>Insert title here</title>
<script>

const proc1 = op =>{ // 매개변수 1개일 땐 가로 생략가능
	let x = parseInt(document.querySelector('#x').value);
	let y = parseInt(document.querySelector('#y').value);
	let sum = 0;
	if(op=='+'){
		sum = add(x,y);
	} else if(op=='-'){
		sum = sub(x,y);
	} else if(op=='*'){
		sum = mul(x,y);
	} else {
		sum = div(x,y);
		sum = sum.toFixed(2);
	}
	
	document.querySelector('#sum').value = sum;
	
	document.querySelector('#sp1').innerText = x;
	document.querySelector('#sp2').innerText = y;
	document.querySelector('#sp3').innerText = sum;
	
}

const add = (x,y) =>{
	return x+y;
}
const sub = (x,y) =>{
	return x-y;
}
const mul = (x,y) =>{
	return x*y;
}
const div = (x,y) =>{
	return x/y;
}
</script>
</head>
<body>

	<div class="box">
		<h3></h3>
		
		x : <input id="x"><br>
		y : <input id="y"><br>
		결과 : <input id="sum"><br><br>
		
		<input type="button" value="확인+" onclick="proc1('+')">
		<input type="button" value="확인-" onclick="proc1('-')"> 
		<input type="button" value="확인*" onclick="proc1('*')"> 
		<input type="button" value="확인/" onclick="proc1('/')"> 
		<br> <br>

		<div id="result1"></div>
		<p>첫번째 값 : <span id="sp1"></span></p>
		<p>두번째 값 : <span id="sp2"></span></p>
		<p>결과 : <span id="sp3"></span></p>
	</div>
</body>
</html>

confirm()

확인 true()

취소 false()


<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="../CSS/public.css"> 
<meta charset="UTF-8">
<title>Insert title here</title>
<script>
const proc1 = () => {
	
	let total = 0;
	let str = "";
	
	while(true){
		// 입력
		input = parseInt(prompt("입력"));
		// 입력값을 더하기
		str += input + " ";
		total+=input;
		
		// break 조건
		if(!confirm("계속 할까요?")){
			disp = ` 더한 값 : ${str} <br> 총합 : ${total}`;
			document.querySelector('#result1').innerHTML=disp;
			break;
		}
	}
}
</script>
</head>
<body>

	<div class="box">
		<h3>수를 하나 입력해서 합을 구한다<br>
		confirm()함수를 이용해서 비교한다</h3>
		<input type="button" value="확인" onclick="proc1()"> <br> <br>

		<div id="result1"></div>
	</div>
</body>
</html>