如何从数组中获取每个连续的元素?
我对JavaScript有些新,我的目标是将数组中的每3个元素放在每3个元素中,并将它们存储为一个数组,以将其推向另一个数组。下面是输出的样子
var a = [11, 2, 3, 4, 5, 6, 7, 8, 9, 2, 2, 3, 4, 5, 4];
就是
var arrays = [[11, 2, 3], [4, 5, 6], [7, 8, 9], [2, 2, 3], [4, 5, 4]]
这些只是整数,但是在我的应用程序中,有一个包含73个对象的数组,这些对象喜欢像这样存储。
var objects = [{}, {}, {}], [{}, {}, {}] ,,,]
基于对象数量的数量,是否有任何问题,因为73不能除以三个
Im a bit new to javascript and my goal is to take every 3 elements in my array and store them as an array to be pushed to another array. Below is what this would look like
var a = [11, 2, 3, 4, 5, 6, 7, 8, 9, 2, 2, 3, 4, 5, 4];
Output would be
var arrays = [[11, 2, 3], [4, 5, 6], [7, 8, 9], [2, 2, 3], [4, 5, 4]]
These are just integers, but in my application, there is an array containing 73 objects which id like to store like this.
var objects = [{}, {}, {}], [{}, {}, {}] ,,,]
would there be any problems based on the number of objects as 73 is not divisible by three
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
像这样的东西,这里的对象是临时的。我正在使用.slice将下一个3组获取,然后将其推到缓冲区阵列上。我将.length用作for循环中的束缚,每次增加3个。
另外,切片可以处理3个不可分解的数组。您可以在此示例中看到剩余的对象在其自己的数组中。
您也可以轻松适应任何n个元素:
让我知道这是否有帮助。
Something like this, the objects are abitrary here. I'm using .slice to get each next group of 3, and pushing it onto the buffer array. I'm using .length as my bound in the for loop and incrementing by 3 each time.
Also, slice can handle arrays that aren't divisible by 3. You can see in this example the leftover object is in its own array.
You can also easily adapt to any n elements:
Let me know if this helps.