I
I
Ivan Sharapenkov2015-04-22 20:25:00
JavaScript
Ivan Sharapenkov, 2015-04-22 20:25:00

JavaScript array cloning. Why is the browser hanging?

function cloneArray(mas) {
  var masClone = new Array();
  for(i = 0; i < mas.length; i++) {
    masClone.push(mas[i]);
    for(j = 0; j < mas[i].length; j++) {
      masClone[i].push(mas[i][j]);
    }
  }
  return masClone;
}

var s1 = 0;
var s2 = 1;
var d1 = 1;
var d2 = 0;

var mass1 = [ 
s = [s1, s2],
d = [d1, d2]
];

var mass2 = cloneArray(mass1);

Here's the code. I just can’t understand why the browser hangs, it’s clear that it’s because of the cycle, but still it seems to be correct.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Ilya Shatokhin, 2015-04-22
@sM0kfyz

There's some kind of magic that I don't understand...

var mass1 = [ 
s = [s1, s2],
d = [d1, d2]
];

Here is the correct deep copy option (example and comparison with other jsfiddle.net/0yseqsuy solutions ):
var isArray = Array.isArray || function (arr) {
  return Object.prototype.toString.call(arr) === "[object Array]";
}

var isObject = function (obj) {
  return Object.prototype.toString.call(obj) === "[object Object]";
}

function cloneDeep(mas) {
  var masClone = isArray(mas) ? new Array(mas.length) : {};   
  
  Object.keys(mas).forEach(function (key) {
    if (isArray(mas[key]) || isObject(mas[key]))
      masClone[key] = cloneDeep(mas[key]);
    else
      masClone[key] = mas[key];
  });

  return masClone;
}

But older browsers need the Object.keys and forEach polyfills.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question