Is there a way to pass an unknown number of arguments like:
var print_names = function(names) {
foreach(name in names) console.log(name); // something li
You can create a function using the spread/rest operator and from there on, you achieved your goal. Please take a look at the chunk below.
const print_names = (...args) => args.forEach(x => console.log(x));
Take advantage of the rest parameter syntax.
function printNames(...names) {
console.log(`number of arguments: ${names.length}`);
for (var name of names) {
console.log(name);
}
}
printNames('foo', 'bar', 'baz');
There are three main differences between rest parameters and the arguments object:
function print_args() {
for(var i=0; i<arguments.length; i++)
console.log(arguments[i])
}
let x = function(){
return [].slice.call(arguments);
};
console.log(x('a','b','c','d'));
arguments.length
. you can use a for loop on it.
(function () {
for (var a = [], i = arguments.length; i--;) {
a.push(arguments[i]);
};
return a;
})(1, 2, 3, 4, 5, 6, 7, 8)
var
print_names = function() {
console.log.apply( this, arguments );
};
print_names( 1, 2, 3, 4 );