Home > Web Front-end > JS Tutorial > body text

How to split array items in JavaScript

醉折花枝作酒筹
Release: 2023-01-04 09:35:07
Original
11519 people have browsed it

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.

How to split array items in JavaScript

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;      //结果是一个数组,里面的元素就是已拆分的小数组
  }
Copy after login

How to split array items in JavaScript

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);
Copy after login
Copy after login

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

How to split array items in JavaScript

var data = [1, 2, 3, 4, 5, 6, 7 ,8 ,9 ,10, 11, 12]
var result = split_array(data, 6);
Copy after login
Copy after login

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.

How to split array items in JavaScript

[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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template