[JS] arguments ๋œฏ์–ด๋ณด๊ธฐ๐Ÿ–

TATAยท2023๋…„ 1์›” 4์ผ
0

JavaScript

๋ชฉ๋ก ๋ณด๊ธฐ
9/25

โœ”๏ธ arguments๋ž€?๐Ÿค”

arguments๋ž€ ํ•จ์ˆ˜์— ์ „๋‹ฌ๋˜๋Š” ์ธ์ˆ˜๋“ค์„ ๋ฐฐ์—ด ํ˜•ํƒœ๋กœ ๋‚˜ํƒ€๋‚ธ ๊ฐ์ฒด์ด๋‹ค.
๋ช‡ ๊ฐœ์˜ ์ธ์ˆ˜๊ฐ€ ์ „๋‹ฌ๋ ์ง€ ๋ชจ๋ฅด๋Š” ์ƒํ™ฉ์—์„œ ํ™œ์šฉํ•˜๋ฉด ์ข‹๋‹ค.

  • arguments ์‚ฌ์šฉ ์˜ˆ์‹œ1
function func1(a, b, c) {
  console.log(arguments[0]);
  // expected output: 1

  console.log(arguments[1]);
  // expected output: 2

  console.log(arguments[2]);
  // expected output: 3
}

func1(1, 2, 3);
  • arguments ์‚ฌ์šฉ ์˜ˆ์‹œ2
function foo(...args) {
  console.log(arguments);
  // [Arguments] { '0': 1, '1': 2, '2': 3 }
}
foo(1, 2, 3);

arguments ์š”์†Œ๋Š” ์žฌํ• ๋‹น๋„ ๊ฐ€๋Šฅํ•˜๋‹ค.

function zoo(a) {
  arguments[0] = 100;
  console.log(a); // 100
}
zoo(10);

But, ๊ธฐ๋ณธ ๋งค๊ฐœ๋ณ€์ˆ˜๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด ์žฌํ• ๋‹น ๋ถˆ๊ฐ€.

function zoo(a = 1) {
  arguments[0] = 100;
  console.log(a); // 10
}
zoo(10);

๐Ÿ– ํ™”์‚ดํ‘œ ํ•จ์ˆ˜์—์„œ์˜ arguments

ํ™”์‚ดํ‘œ ํ•จ์ˆ˜์—๋Š” arguments๋ฅผ ์ •์˜ํ•  ์ˆ˜ ์—†๋‹ค.

๊ทธ๋ž˜์„œ arguments๋ฅผ ์‚ฌ์šฉํ•˜๋ ค๋ฉด ์Šคํ”„๋ ˆ๋“œ ๋ฌธ๋ฒ•(...)์„ ํ™œ์šฉํ•ด์•ผ ํ•œ๋‹ค.
์Šคํ”„๋ ˆ๋“œ ๋ฌธ๋ฒ•์„ ์‚ฌ์šฉํ•˜๋ฉด [object Arguments]๊ฐ€ ์•„๋‹ˆ๋ผ [object Array]๊ฐ€ ์ถœ๋ ฅ๋œ๋‹ค.

์ฆ‰, ๋ฐฐ์—ด๋กœ ๋ฐ”๋กœ ์ถœ๋ ฅ๋˜๊ธฐ์— ํ™œ์šฉ ์‹œ ๋ฐฐ์—ด๋กœ ๋ณ€ํ˜•ํ•ด์ค„ ํ•„์š”๊ฐ€ ์—†๋‹ค.

const arrowFn = (...args) => {
  console.log(args); // [ 'a', 'b', 'c' ]
  console.log(toString.call(args)); // [object Array]
};
arrowFn("a", "b", "c");

๐Ÿ– arguments๋ฅผ ๋ฐฐ์—ด๋กœ ๋ณ€ํ˜•

arguments๋Š” ๋ฐฐ์—ด์ด ์•„๋‹Œ ์œ ์‚ฌ ๋ฐฐ์—ด ๊ฐ์ฒด์ด๋‹ค.
๋•Œ๋ฌธ์— ๋ฐฐ์—ด๋กœ ์‚ฌ์šฉํ•˜๊ณ  ์‹ถ๋‹ค๋ฉด ๋ณ€ํ˜•ํ•˜๋Š” ์ž‘์—…์ด ํ•„์š”ํ•˜๋‹ค.

1. ์Šคํ”„๋ ˆ๋“œ ๋ฌธ๋ฒ• ํ™œ์šฉ

function argsFn(...args) {
  console.log(args); // [ 'a', 'b', 'c' ]
  console.log(toString.call(args)); // [object Array]
};
argsFn("a", "b", "c");

2. Array.prototype.slice.call(arguments)

function argsFn(ar1, ar2, ar3) {
  console.log(toString.call(args)); // [object arguments]

  const arr = Array.prototype.slice.call(arguments); // ๋ฐฐ์—ด๋กœ ๋ณ€ํ™˜
  console.log(arr); // ['a', 'b', 'c']
  console.log(toString.call(arr)) // [object Array]
};
argsFn("a", "b", "c");

3. [].slice.call(arguments)

function argsFn(ar1, ar2, ar3) {
  console.log(toString.call(arguments)); // [object arguments]

  const arr = [].slice.call(arguments); // ๋ฐฐ์—ด๋กœ ๋ณ€ํ™˜
  console.log(arr); // ['a', 'b', 'c']
  console.log(toString.call(arr)); // [object Array]
}
argsFn("a", "b", "c");

์ฐธ๊ณ  ๋งํฌ1 mdn
์ฐธ๊ณ  ๋งํฌ2 ๋ธ”๋กœ๊ทธ

profile
๐Ÿพ

0๊ฐœ์˜ ๋Œ“๊ธ€