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

时间:2014-12-09 16:12:55

标签: javascript arrays

我正在尝试从数组中删除一些元素,并使用splice功能,它也会返回这些值。请参阅以下javascript:

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

尝试运行此行时(与整个函数一起使用),出现以下错误:

  

未捕获的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;
};

然后我以下列方式使用:

var allNumbers = shuffle(blocks);

我尝试记录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;
    }
}

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

由于评论:

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

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

2 个答案:

答案 0 :(得分:5)

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

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

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

答案 1 :(得分:5)

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

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