ν‹°μŠ€ν† λ¦¬ λ·°

728x90

ν•¨μˆ˜μ˜ λ§€κ°œλ³€μˆ˜μ— 아무것도 μ „λ‹¬ν•˜μ§€ μ•ŠμœΌλ©΄ μ–΄λ–»κ²Œ 될까?

a와 bλ₯Ό λ§€κ°œλ³€μˆ˜λ‘œ λ°›μ•„ 두 λ§€κ°œλ³€μˆ˜μ˜ 곱을 λ°˜ν™˜ν•΄μ£ΌλŠ” multiply ν•¨μˆ˜κ°€ μžˆλ‹€κ³  κ°€μ •ν•˜μž.

λ§Œμ•½ μ•„λž˜ μ½”λ“œμ²˜λŸΌ multiply ν•¨μˆ˜λ₯Ό ν˜ΈμΆœν–ˆλŠ”λ° λ§€κ°œλ³€μˆ˜λ₯Ό 전달해주지 μ•ŠλŠ”λ‹€λ©΄ μΈμžλŠ” μ–΄λ–€ νƒ€μž…μ„ κ°€μ§€κ²Œ 될까?

 

function multiply(a, b){
  return a * b;
};

multiply();

 

λ§€κ°œλ³€μˆ˜λ“€μ΄ μ „λ‹¬λ˜μ§€ μ•Šμ€ 경우, console에 각 λ§€κ°œλ³€μˆ˜λ“€μ΄ μ–΄λ–»κ²Œ λ°›μ•„μ™€μ§€λŠ”μ§€ ν™•μΈν•΄λ³΄μž.

function multiply(a, b){
  console.log(a); // undefined
  console.log(b); // undefined
  return a * b;
};

multiply();

μœ„μ˜ μ½”λ“œμ²˜λŸΌ λ§€κ°œλ³€μˆ˜κ°€ μ „λ‹¬λ˜μ§€ μ•Šμ€ 경우, undefined둜 좜λ ₯됨을 μ•Œ 수 μžˆλ‹€.

 

 

 

console.log(multiply()); // NaN

μœ„μ˜ μ½”λ“œμ²˜λŸΌ ν•¨μˆ˜μ˜ return κ°’μ˜ 경우 NaN둜 좜λ ₯λœλ‹€.

 


 

ν•¨μˆ˜μ˜ λ§€κ°œλ³€μˆ˜λ“€μ„ ν•¨μˆ˜ λ‚΄λΆ€μ—μ„œ μ ‘κ·Όν•  수 μžˆλŠ” arguments 객체가 μ‘΄μž¬ν•œλ‹€

function multiply(a, b){
  console.log(a); // undefined
  console.log(b); // undefined
  console.log(arguments);
  return a * b;
};

multiply(2, 4, 6);

μœ„μ˜ μ½”λ“œμ²˜λŸΌ multiply ν•¨μˆ˜μ— 2,4,6을 λ§€κ°œλ³€μˆ˜λ‘œ μ „λ‹¬ν–ˆλ‹€κ³  ν•˜λ©΄,

(multiply ν•¨μˆ˜μ—μ„œλŠ” 맀개 λ³€μˆ˜κ°€ 2개만 ν•„μš”ν•˜λ―€λ‘œ 6은 λ¬΄μ‹œλœλ‹€.)

 

multiply ν•¨μˆ˜ μ•ˆμ—μ„œλŠ” arguments 객체에 λ‹€μŒκ³Ό 같이 μ €μž₯λœλ‹€.

[Arguments] { '0': 2, '1': 4, '2': 6 }

λ”°λΌμ„œ arguments[0], arguments[1] λ“± key 값을 ν™œμš©ν•΄ μ „λ‹¬λœ λ§€κ°œλ³€μˆ˜μ— μ ‘κ·Όν•  수 μžˆλ‹€.

 

 


Rest λ§€κ°œλ³€μˆ˜(Rest Parameters)

λ§Œμ•½ ν•¨μˆ˜μ— λͺ‡ 개의 맀개 λ³€μˆ˜κ°€ 전달될지 λͺ¨λ₯Έλ‹€λ©΄, Rest λ§€κ°œλ³€μˆ˜λ₯Ό μ‚¬μš©ν•  수 μžˆλ‹€.

Rest λ§€κ°œλ³€μˆ˜λŠ” ...λ§€κ°œλ³€μˆ˜λͺ… μ˜ ν˜•μ‹μœΌλ‘œ μ‚¬μš©ν•  수 μžˆλ‹€.

function printMenu(...menus){
  console.log(menus); // [ 'πŸ•', '🍟', 'πŸ”', '🍝' ]
}

printMenu('πŸ•', '🍟', 'πŸ”', '🍝');

μ˜ˆμ‹œλ‘œ μŒμ‹ 메뉴λ₯Ό 좜λ ₯ν•΄μ£ΌλŠ” printMenu ν•¨μˆ˜κ°€ μžˆλ‹€κ³  ν–ˆμ„ λ•Œ,

λͺ‡ 개의 menuκ°€ 전달될 μ§€λŠ” λͺ¨λ₯΄κΈ° λ•Œλ¬Έμ— ...menus λΌκ³  λ§€κ°œλ³€μˆ˜λ₯Ό 섀정해놓은 후에,

ν•¨μˆ˜λ₯Ό ν˜ΈμΆœν•  λ•Œ λ§€κ°œλ³€μˆ˜λ“€μ„ 전달해주면 λœλ‹€.

 

Rest 맀개 λ³€μˆ˜λ₯Ό μ‚¬μš©ν•œ ν•¨μˆ˜μ˜ λ°˜ν™˜ 값은 λ°°μ—΄ ν˜•νƒœλ‘œ λ°˜ν™˜λœλ‹€.

[ 'πŸ•', '🍟', 'πŸ”', '🍝' ]

 

 

 

function print(pizza, fries, ...menus){
  console.log(pizza); //πŸ•
  console.log(fries); //🍟
  console.log(menus); // [ 'πŸ”', '🍝' ]
}

print('πŸ•', '🍟', 'πŸ”', '🍝');

μœ„μ˜ μ½”λ“œμ²˜λŸΌ νŠΉμ • λ§€κ°œλ³€μˆ˜λ₯Ό μ„€μ •ν•˜κ³ , Rest λ§€κ°œλ³€μˆ˜λ₯Ό  ν•¨κ»˜ μ‚¬μš©ν•  μˆ˜λ„ μžˆλ‹€.

728x90

'🟨 JavaScript > ν•¨μˆ˜' μΉ΄ν…Œκ³ λ¦¬μ˜ λ‹€λ₯Έ κΈ€

[JavaScript] ν•¨μˆ˜μ˜ λΆˆλ³€μ„±(Immutability) μ΄λž€?  (0) 2022.12.20
곡지사항
μ΅œκ·Όμ— 올라온 κΈ€
μ΅œκ·Όμ— 달린 λŒ“κΈ€
Total
Today
Yesterday
Β«   2025/02   Β»
일 μ›” ν™” 수 λͺ© 금 ν† 
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28
κΈ€ 보관함
250x250