0

I'd like to write some like this :

Array.prototype.copy(obj_or_array) {
    if (obj_or_array instanceof Array)
    this.array = this.concat ( obj_or_array.slice());
    else    
    for(var key in obj_or_array) {this.push(obj_or_array[key]);}    
}

'this.array' does not exist but I'd like to have it. Any idea ? Is it impossible ?

civiltomain
  • 1,136
  • 1
  • 9
  • 27

2 Answers2

0

Here's the simplest way to clone an array using the method in your question:

if (!('copy' in Array.prototype)) {
  Array.prototype.copy = function() {
    return this.slice(0);
  }
}

var arr = [1, 2, 3, 4];
var arr2 = arr.copy();

And if your objects are always going to be simple (ie they don't have any methods), you could use something like this:

if (!('copy' in Object.prototype)) {
  Object.prototype.copy = function() {
    return JSON.parse(JSON.stringify(this));
  }
}

var obj = { name: 'andy' };
var obj2 = obj.copy();

DEMO

Community
  • 1
  • 1
Andy
  • 61,948
  • 13
  • 68
  • 95
-1

Something like this?

//Error checking and other stuff omitted this is only an EXAMPLE of an IDEA :)
Array.prototype.loadData = function (a)
{
    if(a instanceof Array)
      for(var i =0; i<a.length; i++) 
          this.push(a[i]);

    else if(a instanceof Object)
      for(var i in a) 
          this.push(a[i]);
}
Cipi
  • 11,055
  • 9
  • 47
  • 60
  • Yes, this is what I have. I'd like (but I think it is impossible to access to the array itself to play with map or concat... this.array = this.array.concat(a) (but 'this.array' does not exist) – civiltomain Jan 14 '15 at 11:52
  • Correct, `this.array` does not exist, `this` is the actual array, not `this.array`. How exactly do you want to "play" with that "map"? If you want to add/remove items you will still have to use push or other methods to change that array's state. – Cipi Jan 14 '15 at 13:25
  • I'd like a way to make the job using only one line. From outside you can use Array = AnotherArray.slice() or Array1 =Array1,cancat(Array2( or Arra1 = Array2.map(a_Function...) . The problem is 'How to access to the 'arrayitself' inside the prototype'. The keyword 'this' can be used to use push, etc. But I can't find a way to access to the 'arrayitself' if it'd exis... – civiltomain Jan 14 '15 at 15:30