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');
source to share