[英]Split array into chunks function not working properly | JavaScript
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: 但是,当我在我的网站上用长度为25的数组并将其分为5个块进行测试时,我得到了:
And whenever I test it out on pythontutor.com it functions correctly, does somebody know what the problem is? 每当我在pythontutor.com上对其进行测试时,它都能正常运行,有人知道这是什么问题吗?
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 += pieces
将变成i += "5"
,而i
将变成55
which is why your counter is only running twice. 这就是为什么您的计数器只运行两次的原因。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.