[JS 개념정리] 함수와 반복문

rlorxl·2022년 1월 29일
0

Javascript

목록 보기
1/12
post-thumbnail

function_함수

특정 코드를 하나의 명령으로 실행 할 수 있게 해주는 기능

function 함수이름(파라미터) {return a + b;
 console.log(’호출이 되지 않는 코드’);
}
const sum = add(1,2);
console.log(sum);

분류

1.선언적 방식

function hello() { console.log(’hello1’); } 처럼 function 값이 있는 함수.
특성상 어느 위치에 있던지 먼저 인식이 가능하다.

2.익명함수

(1) hello2 = function() { console.log(’hello2’); }
(2) const hello 3 = funtion() { console.log(’hello3’); }
함수 호출을 위쪽에서 하게 된다면 , (1)의 경우는 undefined, (2)의 경우는 아예 hllo3을 찾지 못하는 결과가 나오게 된다..


arrow(=>)function

const hello1 = (name) => console.log( ‘hello1’ );
const hello4 = name => { return `hello4 ${name}`; }
const hello4 = name => `hello4 ${name}`;
(arrow function은 this를 사용할 수 없다.)

템플릿 리터럴(Template Literal)

문자열을 조합할 때 ‘+’ 대신 편하게 조합을 하는 방법 - ( ‘백틱’ 과 ${} 이용 )
console.log( `Hello, ${name}!` );


예제

1. 파라미터 사용

function plus(first, second) {
  console.log(a + b)
}
plus(6, 10) // 16

2. 객체의 속성에 함수를 정의

const player = {
    name: "ori",
    sayHello: function(otherPersonsName) {
      console.log("hello " + otherPersonsName + " nice to meet you")
    }
  };
  
  console.log(player); // { name: "ori", sayHello: f }
  player.sayHello("lynn"); // hello lynn nice to meet you

3. return

const calculator = {
      add: function(a, b) {
          return a + b;
      }
  };

 const plusResult = calculator.add(1, 1);

한번 return을 작성하고 출력하면 그 함수의 역할은 끝난다. return 뒤쪽으로는 다른 항목 작성X


콜백 함수

다른 함수의 매개변수(파라미터)로 전달되어 수행되어지는 함수.
(여기서 ‘다른 함수'는 ‘고차 함수'라고 부르는데, 매개변수를 통해 함수를 받아 호출하는 함수이다.)

function callback_func(){
  console.log('I'm callback function');
}
function higher_order_func(callback){
  console.log('I'm higher-order funcion');
  callback();
}
higher_order_func(callback_func);

예제-calculator

function add(x,y){
    return x + y;
}
function sub(x,y){
    return x - y;
}
function mul(x,y){
    return x * y;
}
function div(x,y){
    return x / y;
}

function calculator(callback,x,y){
    return callback(x,y);
}

console.log(calculator(add, 7, 3));
console.log(calculator(sub, 7, 3));
console.log(calculator(mul, 7, 3));
console.log(calculator(div, 7, 3));

결과
10, 4, 21, 2.3333333333333335

call by~

1. call by value

‘값에 의한 복사’로 함수 내에서 매개 변수 값을 변경 시켜도 영향이 가지 않는다.
원시타입을 매개 변수로 넘겼을 때 발생.

let a = 1;
let add = function(b){ b = b + 1 };
add(a);
console.log(a); // 1  ( 영향이 가지 않음 )

2. call by reference

‘주소에 대한 복사'로 함수 내에서 매개 변수 내 값을 변경시키면 원본 데이터에도 영향을 미침.
객체타입을 매개 변수로 넘겼을 때.

var a = { v: 1 };
var add = function(b){ b.v = b.v + 1, };
add(a);
console.log(a.v)  // 2 ( b와 a가 주소를 공유하게 되어 a = b 가 된다. )

loop_반복문

for

for(초기화; 반복 조건(true or false); 반복이 된 후 실행되는 코드){
// code
}

for (let i = 0; i < 5; i++) {
  console.log('hi');
} // hi hi hi hi hi

for..of

for...of 명령문은 배열의 개별 속성값(element)에 대해 반복하여 수행한다.

const person = [ “John”, “Bob”,25]
let text = “”;
for(let x of person){
 text += x;
}
console.log(text); // JohnBob25

for..in

객체의 key, value 형태를 반복하여 수행하는데 최적화 된 유형 (배열도 객체이기 때문에 배열 index값을 순회한다.) 첫번째부터 마지막까지, 객체의 키(key) 개수만큼 반복된다.

const person = { fname: 'John', lname: 'Bob', age: '25' };
let text = "";
for(let x in person){
 text += person[x];
}
console.log(text); // JohnBob25
let count = 0;
    let s = '';
    for(let i = 0; i < 1000; i++){ 
        s += i;
    }
    for(let j of s){
        if(j == 1){
            count++;
        }
    }
    /* 위의 for...of와 같은 역할을 하는데 문법이 약간 다르다.
    for(let j in s){
        if(s[j] == 1){ 
            count++;
        }
    }
    */
    console.log(count)

while

조건이 false가 될 때까지 반복 실행
선언문, 증감문없이 loop를 수행하며, 무한 루프등 수행 시 많이 사용한다.

let i = 0;
while (i < 5) {
 console.log(i);
 i++;
} // 0 1 2 3 4

do..while

while뒤의 조건이 거짓이 될 때까지 반복 실행 (무조건 한번은 실행한다.)

i = 4;
do { 
 console.log(i);
 i++;
} while (i < 3); // 4

반복문 제어

break
반복문 수행시 코드 블록을 탈출할 때 사용되는 식별자. 다중 반복문일 경우 가장 안쪽의 반복문 종료.

for (let i = 0; i < 5; i++) {
 console.log(i);if (i > 2)break;
 console.log(’hi', i);} // 0 hi 0 1 hi 1 2 hi 2 3

continue
반복문 수행 시 코드 블록 실행을 해당라인에서 중지하고 반복문 내 명시된 조건(기존 반복 조건) 판단 후 실행

for (let i = 0; i < 5; i++) {
 console.log(i);if (i > 2)continue;
 console.log(’hi', i);} // 0 / hi 0 / 1 / hi 1 / 2 / hi 2 / 3 / 4
profile
즐겜하는거죠

1개의 댓글

comment-user-thumbnail
2024년 3월 3일

Welcome to Inat TV, https://inattv2.com.tr/ Turkey's premier online streaming platform, providing complimentary football content. Ideal for Android users, this app consolidates all your favorite content into one convenient location.

답글 달기