0

Is there a better way to copy an array onto the this variable

function obj(arr) {
  for (var i=0, l=arr.length; i<l; ++i) {
    this[i] = arr[i];
  }
  this.length = arr.length;
}

var o = new obj([1,2,3,4]);
console.log(o[0]); // Outputs 1

Is there any other way to do it, instead of iterating over the whole arr ?

Dano
  • 139
  • 1
  • 7

2 Answers2

2

You can use Array#push this way:

function obj(arr) {
  Array.prototype.push.apply(this, arr);
}

This will treat this like an array, adding all the elements from arr and setting length correctly. See also Function#apply.

But of course there is still an internal loop. You cannot copy / move a collection values to another collection without iterating over it (unless, I guess, the collections use structural sharing)

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
1

You could do it like this:

function obj() {
    return this;
}

var o = obj.apply([1,2,3,4]);
console.log(o[0]); // Outputs 1
dave
  • 62,300
  • 5
  • 72
  • 93