将数组拆分为块功能无法正常工作| JavaScript的

时间:2022-05-27 01:26:17

So I wrote this function that should split a given array into given pieces:

所以我编写了这个函数,它应该将给定的数组拆分成给定的部分:

function makeGrid(array, pieces){
    var i, output = [], temp;
    for (i = 0; i <= array.length; i += pieces){
        temp = array.slice(i, i+pieces);
        output.push(temp);
    }
    return output;
}

But when I test it out on my site with an array of length 25 and into 5 chunks I get this: 将数组拆分为块功能无法正常工作| JavaScript的

但是当我在我的网站上用长度为25的数组和5个数据块进行测试时,我得到了这个:

And whenever I test it out on pythontutor.com it functions correctly, does somebody know what the problem is?

无论何时我在pythontutor.com上测试它都能正常运行,有人知道问题是什么吗?

1 个解决方案

#1


0  

Not sure how to use that but I have an update: whenever I replace $("#input-columns").val() with a real number it works fine

不确定如何使用它,但我有一个更新:每当我用实数替换$(“#input-columns”)。val()时它工作正常

It seems you need to parse the input's value to an integer first

看来你需要先将输入的值解析为整数

makeGrid(tiles, parseInt($("#input-columns").val(), 10))

otherwise i += pieces will become i += "5" and the i becomes 55

否则i + =件将变为i + =“5”并且i变为55

which is why your counter is only running twice.

这就是你的计数器只运行两次的原因。

#1


0  

Not sure how to use that but I have an update: whenever I replace $("#input-columns").val() with a real number it works fine

不确定如何使用它,但我有一个更新:每当我用实数替换$(“#input-columns”)。val()时它工作正常

It seems you need to parse the input's value to an integer first

看来你需要先将输入的值解析为整数

makeGrid(tiles, parseInt($("#input-columns").val(), 10))

otherwise i += pieces will become i += "5" and the i becomes 55

否则i + =件将变为i + =“5”并且i变为55

which is why your counter is only running twice.

这就是你的计数器只运行两次的原因。