1

Anyone knows how to do it (using ES5)? Hello.

Found similar questions in the C++ and C sections, but not in the Javascript one.

var array = [1, 2, 3, 4, 5];
	
//single argument
console.log(array[0]);
	
//dynamic arguments
var item;
for (var i in array) {
	item = array[i];
	console.log("test", item);
	//same as
	//console.log("test", 0);
	//console.log("test", 1);
	//...
}

//Objective: console.log("test", 1, 2, 3, 4, 5);
/*var obj = {};
for (var key in array) {
	obj[key] = array[key];
}
console.log("test", obj[0], obj[1], obj[2], obj[3], obj[4]);
*/
console.log("test", array[0], array[1], array[2], array[3], array[4]);
//need to know the no. of items

3
  • What exactly do you want to achieve? What function need to accept varying number of arguments? What arguments list and how do it varies? Commented Nov 28, 2017 at 9:59
  • And if you just use a two dimensional array instead? Commented Nov 28, 2017 at 10:01
  • Just pass the array directly to whatever number of arguments required! Commented Nov 28, 2017 at 10:02

1 Answer 1

3

You need the spread operator. It destructures your array and passes the items as separate variables.

var array = [1, 2, 3, 4, 5];
	
console.log("test", ...array); // ES6 and higher
console.log.apply(console, ["test"].concat(array)); // ES5

Sign up to request clarification or add additional context in comments.

4 Comments

If the spread operator isn't available then something like: console.log.apply(console, ["test"].concat(array))
Answer apart, I still don't know how the question made sense to you :)
Yeah; can use the ES5 version of spread: github.com/addyosmani/es6-equivalents-in-es5#spread-operator Thanks.
My apology; I forgot. Thanks again.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.