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 ?

6
  • You can refer following post Commented Nov 11, 2015 at 17:26
  • What is your use case for this? Commented Nov 11, 2015 at 17:27
  • @Rajesh the post you mentioned has nothing to do with my question Commented Nov 11, 2015 at 17:27
  • @MikeBrant Study purpose Commented Nov 11, 2015 at 17:28
  • 1
    Dano the answer below is good. But I don't imagine why you need this. It's weird and dangerous. Commented Nov 11, 2015 at 17:29

2 Answers 2

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)

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

Comments

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

2 Comments

Are you aware that this simply returns the array itselft? is this a joke?
This doesn't do any copying which was clearly listed as a requirement.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.