Home > Article > Web Front-end > How to split array items in JavaScript
Methods to split array items: 1. Create a result array; 2. Use the length attribute to obtain the original array length; 3. Use the for statement to loop through the original array according to the array length; 4. In a for loop , use the slice() method to intercept the specified array elements, and use the push() method to assign values to the result array.
The operating environment of this tutorial: Windows 7 system, JavaScript version 1.8.5, Dell G3 computer.
1. Write the processing requirements into a small method. When you need it again next time, just introduce this method and call it.
function split_array(arr, len){ //arr需要拆分的原数组,len小数组包含多少个元素 var a_len = arr.length; var result = []; //结果数组 for(var i=0;i<a_len;i+=len){ result.push(arr.slice(i,i+len)); //循环取原数组N个元素,每次取从上次取的下一个开始取。 } return result; //结果是一个数组,里面的元素就是已拆分的小数组 }
Simple analysis of the code:
The first is the original array that needs to be split, and the second is how much each split array contains elements. (recorded as n). In the loop, the slice method takes n elements of the array, returns them as an array, and returns them to the result.
2. Write the small method and call it to see if the result is correct.
var data = [1, 2, 3, 4, 5, 6, 7 ,8 ,9 ,10, 11, 12] var result = split_array(data, 6);
Split the data data, each array contains 6 elements, the result is as shown in the figure, it is successfully divided into 2 arrays, each with 6 elements
var data = [1, 2, 3, 4, 5, 6, 7 ,8 ,9 ,10, 11, 12] var result = split_array(data, 6);
Split the data data. Each array contains 5 elements. The result is as shown in the figure. It can be seen that it is successfully divided into 3 small arrays, of which the last array has only two elements.
[Recommended learning: javascript video tutorial]
The above is the detailed content of How to split array items in JavaScript. For more information, please follow other related articles on the PHP Chinese website!