How to write a function that accept any number of arguments in JavaScript

2 Answers

0 votes
function f(...args) {
    console.log(args);
}
 
f(1, 4, 5, 7, 3);
f(1, 4, 5);
f(1, 4, 5, 7, 3, 1, 0, 8);
 
 
 
 
/*
run:
 
[1, 4, 5, 7, 3]
[1, 4, 5]
[1, 4, 5, 7, 3, 1, 0, 8]
 
*/

 



answered Feb 4, 2021 by avibootz
0 votes
function f() {
    console.log(arguments);
    console.log(arguments[0] + ", " + arguments[1] + ", " + arguments[2]);
}
 
f(1, 4, 5, 7, 3);
f(9, 2, 1);
f(2, 6, 3, 7, 1, 0, 8);
 
 
 
 
/*
run:
 
[object Arguments] {
  0: 1,
  1: 4,
  2: 5,
  3: 7,
  4: 3
}
"1, 4, 5"
[object Arguments] {
  0: 9,
  1: 2,
  2: 1
}
"9, 2, 1"
[object Arguments] {
  0: 2,
  1: 6,
  2: 3,
  3: 7,
  4: 1,
  5: 0,
  6: 8
}
"2, 6, 3"
 
*/

 



answered Feb 4, 2021 by avibootz
...