Home > Net >  Two forms of a copy function in javascript
Two forms of a copy function in javascript

Time:10-09

There are usually two ways to copy an object. For example, using the C model, one way is you'd pass back a new object, and the second way is you'd write data to an existing object/address. Here are two ways to simulate doing that in JS:

function copy_array(arr) {
    // copy array and return existing array
    const cp = [];
    for(let i=0; i < arr.length; i  )
        cp[i] = arr[i];
    return cp;
}
function copy_to(arr, to_arr) {
    // copy to existing object
    // possible to write to a "reference object", something like `&to_arr`
    to_arr = []
    for(let i=0; i < arr.length; i  )
        to_arr[i] = arr[i];
    return to_arr;
const c = ['a','b','c'];
let arrc=copy_array(c);
const x=[];
copy_to(c, x);

Is it possible to copy objects these two ways? Or is copying to a reference object/address not possible?

CodePudding user response:

For an object you do it essentially the same way, except you use for (key in object) to iterate over the property names.

function copy_to(obj, to_obj) {
  for (let key in obj) {
    to_obj[key] = obj[key];
  }
  return to_obj;
}
  • Related