如何使用 JavaScript 将长数组拆分为较小的数组
我有一组电子邮件(可以是 1 封电子邮件,也可以是 100 封电子邮件),我需要使用 ajax 请求发送该数组(我知道该怎么做),但我只能发送一个包含 10 个或更少电子邮件的数组.因此,如果有 20 封电子邮件的原始数组,我需要将它们分成 2 个数组,每个数组 10 个.或者,如果原始数组中有 15 封电子邮件,然后是 1 个 10 个数组,另一个 5 个数组.我正在使用 jQuery,那么最好的方法是什么?
I have an array of e-mails (it can be just 1 email, or 100 emails), and I need to send the array with an ajax request (that I know how to do), but I can only send an array that has 10 or less e-mails in it. So if there is an original array of 20 e-mails I will need to split them up into 2 arrays of 10 each. or if there are 15 e-mails in the original array, then 1 array of 10, and another array of 5. I'm using jQuery, what would be the best way to do this?
不要使用 jquery...使用普通的 javascript
Don't use jquery...use plain javascript
var a = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15];
var b = a.splice(0,10);
//a is now [11,12,13,14,15];
//b is now [1,2,3,4,5,6,7,8,9,10];
你可以循环这个以获得你想要的行为.
You could loop this to get the behavior you want.
var a = YOUR_ARRAY;
while(a.length) {
console.log(a.splice(0,10));
}
这一次会给你 10 个元素……如果你说 15 个元素,你会得到 1-10,你想要的 11-15.
This would give you 10 elements at a time...if you have say 15 elements, you would get 1-10, the 11-15 as you wanted.