使用array.splice时,Undefined不是函数

Mat*_*ijs 3 javascript arrays

我试图从数组中删除一些元素,并使用splice它还返回这些值的功能.请参阅以下javascript:

var blocksUsed = allNumbers.splice(0,3);
Run Code Online (Sandbox Code Playgroud)

当试图运行这一行(与整个函数一起)时,我收到一条错误说明如下:

未捕获的TypeError:undefined不是函数

我花了很长时间在函数中寻找印刷错误,但似乎没有.我也准备好JQuery是常见的麻烦制造者,但我没有使用JQuery.

通过改组另一个数组来创建数组(shuffle函数不是我的):

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;
};
Run Code Online (Sandbox Code Playgroud)

然后我以下列方式使用它:

var allNumbers = shuffle(blocks);
Run Code Online (Sandbox Code Playgroud)

我尝试记录allNumbers,它正常工作.数组被正确洗牌.然而,尝试对此进行拼接会产生相同的错误.

还要注意我在for循环中进行拼接.代码如下.

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

为什么我不能splice在这个阵列上使用?请注意,如果需要,我可以提供整个功能.我在这个codepen上有完整的功能,可以立即参考.

由于评论:

allNumbers 是包含以下列方式接收的元素的数组的混洗版本:

var blocks = document.getElementsByClassName('block');
Run Code Online (Sandbox Code Playgroud)

epa*_*llo 5

var blocks = document.getElementsByClassName('block');
Run Code Online (Sandbox Code Playgroud)

那不是一个数组.这是阵列.你需要把它变成一个数组.

var elems = document.getElementsByClassName('block');
var blocks = Array.prototype.slice.call( elems, 0 );
Run Code Online (Sandbox Code Playgroud)


Ami*_*oki 5

blocks不是Array.它是一个NodeList所以你需要使用[].slice.call哪个将采用块,这是一个类似数组的结构并返回预期的结果.

var blocksArr = [].slice.call(blocks, 0); 
var blocksUSed = blocksArr.splice(0, 3);
Run Code Online (Sandbox Code Playgroud)