arguments๋ ํจ์์ ์ ๋ฌ๋๋ ์ธ์๋ค์ ๋ฐฐ์ด ํํ๋ก ๋ํ๋ธ ๊ฐ์ฒด์ด๋ค.
๋ช ๊ฐ์ ์ธ์๊ฐ ์ ๋ฌ๋ ์ง ๋ชจ๋ฅด๋ ์ํฉ์์ ํ์ฉํ๋ฉด ์ข๋ค.
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);
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๋ฅผ ์ฌ์ฉํ๋ ค๋ฉด ์คํ๋ ๋ ๋ฌธ๋ฒ(...)์ ํ์ฉํด์ผ ํ๋ค.
์คํ๋ ๋ ๋ฌธ๋ฒ์ ์ฌ์ฉํ๋ฉด [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๋ ๋ฐฐ์ด์ด ์๋ ์ ์ฌ ๋ฐฐ์ด ๊ฐ์ฒด์ด๋ค.
๋๋ฌธ์ ๋ฐฐ์ด๋ก ์ฌ์ฉํ๊ณ ์ถ๋ค๋ฉด ๋ณํํ๋ ์์
์ด ํ์ํ๋ค.
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");