2024.04.04
함수
<script type="text/javascript">
//선언적 함수
function check(){
document.write('호출하면 동작함<br>');
}
//함수 호출
check();
//인자 앞에 var를 명시하면 오류 발생
function check2(msg){
document.write(msg + '을 좋아합니다.<br>');
}
//함수 호출
check2('가을');
function check3(num){
return num*num;
}
//함수 호출
var number = check3(10);
document.write('number = ' + number + '<br>');
//익명 함수
var play = function(){
document.write('운동을 좋아해요~~<br>');
};
//함수 호출
play();
var play2 = function(item){
document.write(item + '를 좋아해요<br>');
};
//함수 호출
play2('축구');
var play3 = function(x,y){
return x + y;
};
//함수 호출
var result = play3(5,8);
document.write('result = ' + result + '<br>');
//정의한 함수를 인라인 방식으로 호출하기
function checkIt(){
alert('인라인 방식으로 함수 호출하기');
}
</script>
함수 사용시 주의사항
<script type="text/javascript">
//함수의 이름이 같을 경우 마지막 함수 호출
function 함수(){
document.write('함수 A<br>');
}
function 함수(){
document.write('함수 B<br>');
}
//함수 호출
함수();
document.write('---------------<br>');
//함수 호이스팅
함수2();
function 함수2(){
document.write('함수2<br>');
}
document.write('---------------<br>');
//변수 선언은 중복될 수 있고 호출은 마지막 변수가 호출됨
var 함수3 = function(){
document.write('함수 C<br>');
};
var 함수3 = function(){
document.write('함수 D<br>');
};
//함수 호출
함수3();
document.write('---------------<br>');
//함수 호이스팅이 아니라 변수 호이스팅으로 인식
//함수처럼 호출하면 오류 발생
//함수4();
var 함수4 = function(){
document.write('함수4');
};
</script>
지역변수와 전역변수
<script type="text/javascript">
/*
1.지역변수(함수 레벨 스코프)
함수안에서 var를 사용해서 선언한 변수, 함수가 끝나면 소멸
2.전역변수
함수밖에서 만들어진 모든 변수
함수안에서 var없이 만들어진 변수
함수가 끝나도 메모리에 남아 있음
*/
function test1(){
var i = 10; //지역변수
document.write(i + '<br>');
}
test1();
//지역변수는 함수가 종료되면 소멸되기 때문에
//함수 밖에서 호출 불가능
//document.write(i + '<br>');
//전역변수
var j;
function test2(){
j = 200;
document.write(j + '<br>');
}
test2();
function test3(){
document.write(j + '<br>');
}
test3();
//전역변수
//var를 명시하지 않고 전역변수를 만들면 선언과 함께 초기화해야 함
a = 10;
function test4(){
document.write(a + '<br>');
}
test4();
//전역변수
//함수내에서 var를 명시하지 않고 변수를 선언하면 전역변수
function test5(){
m = 300; //전역변수
document.write(m + '<br>');
}
test5();
document.write(m + '<br>');
</script>
let
<script type="text/javascript">
/*
블록 레벨의 스코프 : let(변수), const(상수)
*/
//let를 블록 레벨 지역변수로 사용
//for문안에서 지역변수 선언
for(let i=1;i<=3;i++){
document.write(i + '<br>');
}
document.write('-----------<br>');
//document.write(i);//for문 블럭을 벗어나면 호출 불가
for(var x=1;x<=3;x++){
document.write(x + '<br>');
}
document.write(x + '<---전역적으로 인식<br>');
document.write('-----------<br>');
function test1(){
let i = 100;
document.write(i + '<br>');
}
test1();
//함수안에서 선언되었기 때문에 함수를 벗어나서는 호출 불가
//document.write(i + '<br>');
document.write('-------------<br>');
//let를 전역변수로 사용
let i = 10;
function test2(){
document.write(i + '<br>');
}
test2();
document.write(i + '<---전역적으로 사용<br>');
document.write('------------<br>');
let a = '사과';
//let로 변수 정의시 변수명 중복 불허
//let a = '포도';
document.write('a = ' + a + '<br>');
document.write('------------<br>');
//let를 명시하면 변수 호이스팅이 적용되지 않음
//document.write(b);
let b;
</script>
const
<script type="text/javascript">
const a = 10; //상수
document.write(a + '<br>');
document.write('------------<br>');
//상수는 변경 불가능
//a = 20;
//document.write(a + '<br>');
function test(){
const b = 20;
document.write(b + '<br>');
}
test();
//const는 블럭 레벨 스코프로 동작하기 때문에
//함수 블럭을 벗어나면 호출 불가
//document.write(b);
</script>
함수의 인자
<script type="text/javascript">
/*
자바스크립트는 함수를 생성할 때 지정한 매개변수보다 많거나 적은 매개변수를 사용하는
것을 허용. 원래 함수에서 선언한 매개변수보다 적게 사용하면 미지정 매개변수에
undefined가 입력됨
*/
function test(a,b){
document.write('a = ' + a + '<br>');
document.write('b = ' + b + '<br>');
}
test();
document.write('------------<br>');
test(10);
document.write('------------<br>');
test(10,20);
document.write('------------<br>');
test(10,20,30);
</script>
나머지 매개변수
<script type="text/javascript">
/*
나머지 매개변수는 매개변수를 정의할 때 정해지지 않은 매개변수들을 정의할 수 있게 함.
arguments 객체와 유사하나 arguments 객체는 함수에 전달되는 모든 전달
인자를 포함하는 반면에, 나머지 매개변수는 정해지지 않는 나머지를 의미함.
*/
function test1(...args){
document.write('args : ' + args + '<br>');
}
test1(10,20,30);
function test2(a,b,...others){
document.write('a : ' + a + '<br>');
document.write('b : ' + b + '<br>');
document.write('others : ' + others + '<br>');
}
test2(10,20,30,40,50);
</script>
return
<script type="text/javascript">
function returnTest(){
document.write('문장A<br>');
for(let i=1;i<=10;i++){
//조건문
if(i == 5){
//특정 조건일 때 반복문을 빠져나감
//break;
//함수를 호출한 곳으로 되돌아감
//결과적으로 함수 종료
return;
}
document.write(i + '<br>');
}
document.write('문장B<br>');
}
//함수 호출
returnTest();
document.write('프로그램 끝!!');
</script>
화살표 함수
<script type="text/javascript">
/*
ES6에서 도입된 화살표 함수(arrow function)은 function 키워드 대신
화살표(fat arrow =>)를 사용해 좀 더 간략한 방법으로 함수를 선언할 수 있다.
화살표 함수는 항상 익명 함수로 정의한다.
*/
let print = (x) => {
document.write(x);
};
print(10);
document.write('<br>-----------<br>');
let print2 = (x) => {
return x + 10;
};
document.write(print2(10));
document.write('<br>-----------<br>');
let print3 = (x,y) => {
return x * y;
};
document.write(print3(3,6));
document.write('<br>-----------<br>');
//매개변수가 하나일 경우에는 인자를 정의할 때 괄호를 생략할 수 있음
let print4 = x => {
return x * 10;
};
document.write(print4(5));
document.write('<br>-----------<br>');
//화살표 함수 코드 블록을 지정하지 않고 한 문장으로 작성시 return문을
//않아도 화살표 오른쪽 표현식의 계산 결과값이 반환됨
let print5 = (x,y) => x*y;
document.write(print5(2,3));
</script>
내부함수(클로저 현상)
<script type="text/javascript">
function f(){
let n = 123;
//내부함수
function g(){
document.write('n = ' + n + '<br>');
document.write('g함수 호출');
}
return g; //내부함수 반환
}
//함수 호출
let m = f();
document.write(m + '<br>');
document.write('----------------<br>');
//반환된 내부함수 호출
//f함수가 종료되고 f함수의 지역변수 n은 소멸해야 하지만
//지역변수 n는 남겨둠으로써 내부함수가 호출될 때 값이 정상적으로
//출력될 수 있도록 처리해줌. 이렇게 지역변수가 남겨지고 지역변수를
//사용할 수 있는 현상을 클로저라고 부름
m();
</script>
isFinite함수
<script type="text/javascript">
let number1 = 10 / 0;//Infinity
document.write('number1 = ' + number1 + '<br>');
let number2 = -10 / 0;//-Infinity
document.write('number2 = ' + number2 + '<br>');
//isFinite함수를 이용해서 0으로 나누었는지 판단
if(isFinite(number2)){//0이 아닌 수로 나눈 경우
document.write('0이 아닌 수로 나눔');
}else{//0으로 나눈 경우
document.write('0으로 나눔');
}
</script>
isNaN함수
<script type="text/javascript">
let number1 = 10 / 'A';//NaN(Not a Number)
document.write('number1 = ' + number1 + '<br>');
//항상 false로 반환하기 때문에 isNaN함수를 사용해야 함
if(number1 == NaN){
document.write('숫자가 아님<br>');
}else{
document.write('숫자임<br>');
}
document.write('---------------<br>');
//전달되는 인자의 값이 숫지인지 아닌지 판단
if(isNaN(number1)){
document.write('숫자가 아님<br>');
}else{
document.write('숫자임<br>');
}
</script>
parseInt(),parseFloat()
<script type="text/javascript">
let num = '1234';
let won = '1000원';
let won2 = '원1000';
document.write(Number(num) + '<br>');//string -> number
document.write(Number(won) + '<br>');//NaN
document.write(parseInt(num) + '<br>');
//앞의 숫자만 추출해서 형변환
document.write(parseInt(won) + '<br>');
//처음에 문자가 등장하면 형변환할 수 없음
document.write(parseInt(won2) + '<br>');
document.write('-----------------<br>');
let num2 = '24.56';
let dollar = '1.5$';
let dollar2 = '$1.5';
document.write(Number(num2) + '<br>');//string->number
document.write(Number(dollar) + '<br>');//NaN
document.write(parseFloat(num2) + '<br>');
document.write(parseFloat(dollar) + '<br>');
document.write(parseFloat(dollar2) + '<br>');//NaN
document.write('-----------------<br>');
let no1 = '10';
let no2 = '3.67';
//소수점 이하 절삭
document.write(parseInt(no2) + '<br>');
document.write(parseFloat(no1) + '<br>');
</script>
encoding함수
/*
함수 이름 설명
escape(url) 적절한 정도로 인코딩함
unescape(url) 적절한 정도로 디코딩함
encodeURI(url) 최소한의 문자만 인코딩함
decodeURI(url) 최소한의 문자만 디코딩함
encodeURIComponent(url) 대부분의 문자를 인코딩함
decodeURIComponent(url) 대부분의 문자를 디코딩함
*/
const URL = '<<a href=http://www.naver.com?test=한글입니다.'>http://www.naver.com?test=한글입니다.'</a>>;
//출력용 변수 선언 및 초기화
let output = '';
output += '*escape()<br>';
output += escape(URL) + '<br><br>';
output += '*encodeURI()<br>';
output += encodeURI(URL) + '<br><br>';
output += '*encodeURIComponent()<br>';
output += encodeURIComponent(URL) + '<br><br>';
document.write(output);
eval 함수
<script type="text/javascript">
//eval(string) : string을 자바스크립트 코드로 실행
let willEval = '';
//(주의);를 명시해야 동작함
willEval += 'var number = 10;';
willEval += 'alert(number);';
eval(willEval);
alert(number);
</script>
배열의 요소 추가
<script type="text/javascript">
//자바스크립트의 배열은 가변 길이이기 때문에 요소의 추가,삭제 가능
const array = ['포도','사과'];
// 0 1
//배열의 요소 목록 출력
//쉼표(,)로 구분한 문자열 반환
document.write(array + '<br>');
array[2] = '사과';//인덱스 2에 요소를 대입해서 요소의 개수가 늘어남
document.write(array + '<br>');
array[10] = '망고';
document.write(array + '<br>');
//건너뛴 요소의 인덱스를 호출하면 undefined 값이 반환
document.write(array[4] + '<br>');
</script>
배열의 요소 삭제
<script type="text/javascript">
const array = ['one','two','three'];
// 0 1 2 length = 3
document.write(array + '<br>');
array.length = 2; //마지막 데이터 삭제
document.write(array + '<br>');
array.length = 4;//길이가 증가함
document.write(array + '<br>');
document.write('-------------<br>');
const array2 = ['서울','부산','대구','광주'];
// 0 1 2 3
delete array2[1];//제거한 위치에 빈 요소를 남김
document.write(array2 + '<br>');
document.write('-------------<br>');
const array3 = ['한국','미국','일본','중국','호주'];
// 0 1 2 3 4
//인덱스 2에 해당하는 요소부터 하나의 요소를 제거하고 그 위치에 다음 인덱스의
//데이터가 이동하여 위치함
array3.splice(2,1);
document.write(array3);
</script>