The maximum size of the call stack when splitting

Trying to duplicate an Agar function , but when I call it, the maximum call stack size is exceeded. ( JSFiddle ) [note: do not click on the canvas because this will call the split function)

This is the fragment that causes the overflow:

this.cells.push({
    coords: {
        x: this.cells[i].coords.x + 50,
        y: this.cells[i].coords.y
    },
    mass: this.mass,
    velocity: {
        x: this.cells[i].velocity.x,
        y: this.cells[i].velocity.y
    },
    hue: this.cells[i].hue
});

This only happens when I click something in this.cells. Modifying this.cells in any other way or clicking on other arrays or something else works fine. Note that clicking on this.cells outside the for loop that is currently working works fine. (does not produce the desired effect, but does not cause overflow, as the current one does)

split ?

+4
1

split:

for (var i = 0; i < this.cells.length; i++)

length of cell , , -, i , .

:

// Get the init value of the length, 
// so push something into this.cells won't make it unable to end.
var length = this.cells.length;
for (var i = 0; i < length; i++) {

, .

// Start at the end of the array, if the order is not a concern.
for (var i =  this.cells.length - 1; i >= 0; i--)

.

, ,

this.cells.push({
    coords: {
        x: this.cells[i].coords.x + 50,
        y: this.cells[i].coords.y
    },
    mass: this.mass,
    velocity: {
        x: this.cells[i].velocity.x,
        y: this.cells[i].velocity.y
    },
    hue: this.cells[i].hue
});

this.cells.push({
    coords: {
        x: this.cells[i].coords.x + 50,
        y: this.cells[i].coords.y
    },

    // this.mass is undefined, I believe you intend to get the current cell mass here.
    mass: this.cells[i].mass,

    velocity: {
        x: this.cells[i].velocity.x,
        y: this.cells[i].velocity.y
    },
    hue: this.cells[i].hue
});

. jsfiddle, reverse ver.

+3

Source: https://habr.com/ru/post/1618838/


All Articles