Using prototypes, you need to copy the values ​​of the array and duplicate them into a new array.
That is, there is
[1,2]
need to
[1,2].ocopy()
returned the result [1,2,1,2].

 <script type="text/javascript"> var co = function() { var nor = [], count = Object.keys(this).length; for(var i = 0; i < count; i++) { nor.push(this[i]); nor.push(this[i]); } return nor; } Object.prototype.ocopy = co(); console.log([1,2].ocopy()); </script> 

In this form, the code does not work at all, and this in the co () function generally understands that we are accessing the window.

Where is the mistake?

  • Your solution and should not work. Even if you forget about this it has nothing to do with copying elements. - Dmitriy Simushev
  • yes, part of the copy has not written yet, because it makes no sense, because this does not take what you need - mix
  • Object.prototype.ocopy = co(); - you assign the result of the function, i.e. count , not the function itself. - etki
  • [1,2].ocopy() should return 2, and returns '[1,2] .ocopy is not a function' - mix
  • @ Sh.Khachatryan why should he return 2 ?! according to the conditions of the problem, he must return [1,2,1,2] . You would have first decided what exactly you need. - Dmitriy Simushev

1 answer 1

For your purposes, the built-in function Array.prototype.concat() suitable; it takes, as arguments, n arrays, which must be merged into one.

 Array.prototype.ocopy = function() { var newArray = []; newArray = newArray.concat(this, this) return newArray; }; 

Laconic it will look like this:

 Array.prototype.ocopy = function() { return [].concat(this, this); }; 

Your mistake is that you assign to the object's method the result of the function, and not the function itself. That is, it would be necessary to do this: Object.prototype.ocopy = co;

PS I note that to edit the prototypes of existing types is considered not very good form. This action is too global and we must make sure that this does not lead to ambiguities in the future.

  • 3
    return [].concat(this, this); looks clearer :) - Dmitriy Simushev
  • 2
    @DmitriySimushev, the task was to show visibility for a person who is not tempted by such constructions. I think a good minifier would do it for a person. - Rolandius