
In the default case like above, this will be the a new Array instance using the Array of the realm associated with the this value. In ES6 slice returns an object that is determine based upon the actual this value passed to slice. The problem is that in ES<6 slice always returned a new Array instance using the Array of the realm associated with the invoked slice function. instanceof is not a reliable test for array-ness when objects flow between realms.

var g = newGlobal( "new-compartment") //or any non-standard mechanism to get a handle on another realm's global objectĪlso note that if the instanceof tests above were replaced with Array.isArray(g.a) you would get all trues in both ES5 and ES6. Here is one of the test cases André is talking about. To make a deep copy, JSON can be used but it has some limitations such as not working with functions or objects containing circular references.Very interesting. These methods create a shallow copy of the original array which only copies the first level of data. The blog post explains that there are three common ways to copy an array in JavaScript: the slice method, spread operator and om method. But for basic data structures, it’s an easy way to create a deep copy. This approach has some limitations: it doesn’t work with functions or objects containing circular references. Here’s an example using JSON:Ĭonst originalArray = Ĭonst copiedArray = JSON.parse(JSON.stringify(originalArray)) If you have an array of objects or arrays, you may need to create a deep copy to copy the nested data as well.

Here are three common ways:Ĭonst copiedArray = originalArray.slice() Ĭonst copiedArray = om(originalArray) Īll these methods create a shallow copy of the original array, which means they can only copy the first level of the original array. In JavaScript, you can copy an array using various methods. We will also look at how to create a deep copy using JSON when dealing with nested data structures such as objects or arrays containing circular references. Are you looking for a way to copy an array in JavaScript? In this blog post, we’ll discuss three common methods of copying arrays: the slice method, spread operator and om method.
