0

I have implemented a simple method to clone an array.

Array.prototype.clone = function () {
    return JSON.parse(JSON.stringify(this));
};

If I use this code, all arrays in my application have the last element that is this clone function!

enter image description here

Any ideas? xD

Thank you.

3
  • This is expected since you are extending the Array prototype object. Commented Oct 4, 2018 at 12:28
  • I don't see it in the array, it is on prototype. Also note that the length of array is 4 having four elements, clone is not defined on that array. Why did you implemented a simple method to clone when you could use .slice(0) to create copy of an array? Commented Oct 4, 2018 at 12:30
  • @Tushar Thank you, but in the latest version of Chrome .slice(0) doesn't works. Commented Oct 4, 2018 at 12:42

2 Answers 2

1

Simply set your function to non enumarable.

Object.defineProperty(Array.prototype, 'clone', {
    enumerable: false,
    value: function () { return JSON.parse(JSON.stringify(this)); }
});
Sign up to request clarification or add additional context in comments.

Comments

0

It is based on the editor console that you are using. It may show the customised function (clone function)in the index area and not as a native method in array prototype section.It not a thing to be worried as the index is 4 it takes only the elements upto index 0 to 3.

The Screenshot of Customized function in the prototype section

Comments

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.