Home >Web Front-end >Front-end Q&A >How to convert array to list in javascript
With the continuous development of front-end technology, JavaScript has become an important part of the front-end development world. In front-end development, processing data operations is a very important task.
In JavaScript, one of the ways to store data is an array. Sometimes, we need to convert the array into a list (List) form. For example, when rendering data, we need to display the data in an ordered list.
This article will introduce how to use JavaScript to convert an array into a list, and provide sample code for several different ways.
Method 1: Use for loop
Use for loop to iterate through each element in the array and insert them into the list using innerHTML. The following is a sample code:
var arr = ["苹果", "香蕉", "橘子", "西瓜", "葡萄"]; var list = document.createElement("ul"); for(var i = 0; i < arr.length; i++){ var item = document.createElement("li"); item.innerHTML = arr[i]; list.appendChild(item); } document.body.appendChild(list);
Method 2: Use the map function
Arrays in JavaScript have a map function, which can pass each element in the array and their subscripts as parameters Gives a function and returns the result as a new array.
We can use the map function to convert the array into a new array containing list elements and insert them into the list. The following is a sample code:
var arr = ["苹果", "香蕉", "橘子", "西瓜", "葡萄"]; var list = document.createElement("ul"); var listItems = arr.map(function(item){ return "<li>" + item + "</li>"; }); list.innerHTML = listItems.join(""); document.body.appendChild(list);
Method 3: Use the join function
The join function in JavaScript can connect all the elements in the array into a string, and we can format them in HTML Concatenates a string containing the list elements and inserts them into the list.
The following is sample code:
var arr = ["苹果", "香蕉", "橘子", "西瓜", "葡萄"]; var list = document.createElement("ul"); var listStr = "<li>" + arr.join("</li><li>") + "</li>"; list.innerHTML = listStr; document.body.appendChild(list);
The above are three methods of converting arrays into lists. In practical applications, we can choose different methods according to specific needs.
When using the above code, remember to encapsulate it in a function and pass in the array as a parameter. This way the code will be more reusable.
The above is the detailed content of How to convert array to list in javascript. For more information, please follow other related articles on the PHP Chinese website!