gpt4 book ai didi

javascript - 使用 array.splice 时未定义不是函数

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:07:52 25 4
gpt4 key购买 nike

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

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

当尝试运行这一行(连同整个函数)时,我收到一条错误消息:

Uncaught TypeError: undefined is not a function

我花了很多时间寻找函数中的打印错误,但似乎没有。我也知道 JQuery 是这里常见的麻烦制造者,但我没有使用 JQuery。

数组是通过打乱另一个数组创建的(打乱函数不是我的):

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');

最佳答案

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

那不是数组。它类似于数组。你需要把它做成一个数组。

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

关于javascript - 使用 array.splice 时未定义不是函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27383611/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com