Rest Parameters (...)

About

JavaScript์˜ Rest parameter(...) ๋ฌธ๋ฒ•์€ ํ•จ์ˆ˜๊ฐ€ ๋ช…์‹œ๋˜์ง€ ์•Š์€ ๊ฐฏ์ˆ˜์˜ ๋งค๊ฐœ๋ณ€์ˆ˜๋ฅผ ๋ฐฐ์—ด๋กœ ๋ฐ›์„ ์ˆ˜ ์žˆ๋„๋ก ํ•œ๋‹ค.

Java์—์„œ๋Š” ๊ฐ€๋ณ€์ธ์ž (Varargs)๋กœ ์•Œ๋ ค์ ธ ์žˆ๋‹ค.

Syntax

function f(a, b, ...theArgs) {
  // ...
}

f(3, 4, 5, 6, 7, 8, 9, 10)
  • .์„ ์„ธ๊ฐœ ์ฐ์–ด ...๋กœ ๋งŒ๋“ค์–ด ๋งค๊ฐœ๋ณ€์ˆ˜ ์•ž์— ๋‘๋ฉด rest parameter๋กœ ์ธ์‹๋œ๋‹ค.

  • a, b ๋’ค์— ๋‚˜์˜ค๋Š” 3, 4, ..., n๋ฒˆ์งธ ๋ณ€์ˆ˜๋Š” ๋ชจ๋‘ theArgs ์•ˆ์— ๋“ค์–ด๊ฐ„๋‹ค.

    • a, b๋Š” ๊ฐ๊ฐ 3, 4, ๊ทธ๋ฆฌ๊ณ  theArgs๋Š” [5, 6, 7, 8, 9, 10]์ด ๋œ๋‹ค.

Caution

Note: ํ•จ์ˆ˜๋Š” ๋ฐ˜๋“œ์‹œ ํ•˜๋‚˜์˜ ... rest parameter์„ ๊ฐ€์งˆ ์ˆ˜ ์žˆ๋‹ค.

// Wrong!
foo(...one, ...wrong, ...wrong)

Note: Rest parameter๋Š” ํ•จ์ˆ˜ ์ •์˜์—์„œ ๋งจ ๋งˆ์ง€๋ง‰ ๋งค๊ฐœ๋ณ€์ˆ˜๊ฐ€ ๋˜์–ด์•ผ ํ•œ๋‹ค.

// Wrong!
foo(...wrong, arg2, arg3)

Note: ๋งž๋Š” ์˜ˆ์‹œ

foo(arg1, arg2, ...correct)

REF

MDN Web Docs - Rest parameters

Last updated