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
Ramsing Nadeem
  • 101
  • 1
  • 12

1 Answers1

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
Suren Srapyan
  • 66,568
  • 14
  • 114
  • 112