JavaScript Array Prototype Clone Multiple dimensional array

Description

JavaScript Array Prototype Clone Multiple dimensional array


// A simple clone function
Array.prototype.clone: function() {
    return [].concat(this);
}

// A multi-dimensional array clone function
Array.prototype.cloneMulti = function() {
    let myArr = [].concat(this);
    for (let i = 0, len=myArr.length; i < len; i++)
        if (Object.prototype.toString.apply(myArr[i]) === '[object Array]')
            myArr[i] = myArr[i].clone();
    return myArr;
}

let myMultiDimArray = [
  ["hello", "world"],
  ["something", "else"],
  [1,2,3,4]//  ww w . j  ava2s. c  o m
];

let myArrayCopy = myMultiDimArray.cloneMulti();

myMultiDimArray[0][0] = "bla";

console.log( myArrayCopy[0][0] ); // "hello"



PreviousNext

Related