Undefined is not a function when using array.splice

I am trying to remove some elements from an array and use functionality splice

where it returns those values ​​as well. See the javascript below:

var blocksUsed = allNumbers.splice(0,3);

      

When I try to run this line (combined with the whole function), I get the error:

Uncaught TypeError: undefined is not a function

I've spent quite a bit of time looking for typographical errors in the function, but there don't seem to be any. I am also prepared that JQuery is a common problem-breaker, but I am not using JQuery.

The array is created by shuffling another array (the shuffle function is not mine):

function shuffle(o){
    for(var j, x, i = o.length; i; j = Math.floor(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
    return o;
};

      

which I then use like this:

var allNumbers = shuffle(blocks);

      

I have tried recording allNumbers which works correctly. The array is shuffled correctly. Trying to do a splice on this, however, gives the same error.

Also note that I am doing the splice inside a for loop. The code is below.

for (var i = 0; i < 4; i++){

    // Get a block of 3 blocks.
    var blocksUsed = allNumbers.splice(0,3); // This line gives the error.

    // Determine the color used for these blocks and remove it so that it doesn't get drawn again.
    var colorIndex = randomIntFromInterval(0,i);
    var colorUsed = otherColors[colorIndex];
    if(otherColors.indexOf(colorUsed) > -1){
        otherColors.splice(colorIndex, 1);
    }

    // For each block, set the color.
    for(var j = 0; j < 3; j++){
        blocksUsed[j].className = "block " + colorUsed;
    }
}

      

Why can't I use splice

on this array? Please note that I can provide the entire function if needed. I have all the function in this codepen to link at once.

Because of the comment:

allNumbers

is a shuffled version of the array containing elements obtained as follows:

var blocks = document.getElementsByClassName('block');

      

+3


source to share


2 answers


var blocks = document.getElementsByClassName('block');

      

It is not an array. It's an array like. You need to do this into an array.



var elems = document.getElementsByClassName('block');
var blocks = Array.prototype.slice.call( elems, 0 );

      

+5


source


blocks

is not Array

. This is a NodeList

Therefore you need to use [].slice.call

that will take blocks that are an array type structure and return the expected results.



var blocksArr = [].slice.call(blocks, 0); 
var blocksUSed = blocksArr.splice(0, 3);

      

+5


source







All Articles