You can rewrite this without a for
loop, but you have to use a loop of some sort (you're working with multiple items, it's a necessity).
If you have access to ES6 or Babel, I would use something like:
function append(...args) {
return array.concat(args);
}
Without ES6, you need to work around the fact that arguments
isn't a real array. You can still apply most of the array methods to it, by accessing them through the Array
prototype. Converting arguments
into an array is easy enough, then you can concat
the two:
function append() {
var args = Array.prototype.map.call(arguments, function (it) {
return it;
});
return array.concat(args);
}
Bear in mind that neither of these will modify the global array
, but will return a new array with the combined values that can be used on its own or assigned back to array
. This is somewhat easier and more robust than trying to work with push
, if you're willing to array = append(...)
.