Jonas
Jonas

Reputation: 7915

JavaScript remove index of array not working

I have this Array:

var sizes = [
        [20, 10, 0],
        [40, 20, 0],
        [60, 30, 0],
        [80, 40, 0],
        [100, 50, 0]
        ];

I want to randomly change the size of rectangle to to the sizes: (20, 10) or (40, 20) or (60, 30) or (80, 40) or (100, 50) and I change the X Position(this does not to seem part of my Problem)

Every Size can only be displayed a maximum of 10 times. I save the counter of the size in the 3rd column of the Array. And when it counts 10 I want to delete this size of the possible sizes, so it can't be changed to this size again. Also this should limit the changes to a maximum of 50 times.

My Code to randomly change the rectangle looks like this:

function changeRec() {

        if (sizes.length == 0) {
            return;
        }

        var rnd = Math.round(Math.random() * (sizes.length -1 ));

        var x = sizes[rnd][0];
        var y = sizes[rnd][1];

        var element = document.getElementById("rectangle");

        element.style.width = x + "px";
        element.style.height = y + "px";

        var newX = (Math.random() * (document.body.clientWidth -200));
        var rect = element.getBoundingClientRect();
        if (Math.abs(newX - rect.left) < 30) {
            changeRec();
        } else {
            element.style.left = newX+"px";
            sizes[rnd][2]++;

            if (sizes[rnd][2] == 10) {
                delete sizes[rnd];
                console.log("deleted");
            }

            count++;
            calculate();
        }           
    }

However this code does not seem to work properly. I don't really know why but It seems like the removing from an index of the sizes array does not work.

I get the Error: TypeError: undefined is not an object (evaluating 'sizes[rnd][0]')

Upvotes: 1

Views: 869

Answers (1)

Bunyamin Coskuner
Bunyamin Coskuner

Reputation: 8859

delete sizes[rnd] will not shrink your array by one, instead it'll give you an empty element. Therefore, when you hit that index second time, it'll throw an error.

To remove an item from an array you should use splice.

Change

delete sizes[rnd]

to

sizes.splice(rnd, 1)

Upvotes: 3

Related Questions