简体   繁体   English

如何在JavaScript中将项目追加到嵌套数组

[英]How to append items to nested array in JavaScript

I have an outer JS array 'main_category' which should contain several arrays within it called 'temp'. 我有一个外部JS数组“ main_category”,其中应包含多个名为“ temp”的数组。

The array temp contains several string elements taken from an li tag. 数组temp包含从li标签中获取的几个字符串元素。

In order to populate both the arrays I am running a for-loop through each li tag for each ul tag in the html page, as shown below: 为了填充这两个数组,我通过html页面中的每个ul标签的每个li标签运行一个for循环,如下所示:

function a{
   var category_list = [];
   var temp;

   //how to split this list iteration into two for-loops
   $(".ul_list li").each(function(){
       temp = [];
       //adding only those list elements of a ul, that are red in color
       if($(this).attr("style") == "color:red"){
          var cat = $(this).text();
          cat = cat.replace(/\s\s+/g, ' '); //removes whitespaces
          temp.push(cat); //creates a single array for a single element
       }
    }
    category_list.push(temp);  
   });
 }

Desired output : 所需输出

  category_list = [['l1', 'l2', 'l3'], ['l1', 'l2', 'l3'], ['l1', 'l2', 'l3']..]

Current output : 电流输出

   category_list = [['li'], ['l2'], ['l3']...]

However, the temp.push(cat) LOC creates a temp array for each individual li element instead of creating a temp=[] for all the li elements within one ul. 但是,temp.push(cat)LOC为每个单独的li元素创建一个temp数组,而不是为一个ul中的所有li元素创建temp = []。

You can do this through iterating through each .ul_list element then their children in that order should give you the expected result. 您可以通过遍历每个.ul_list元素来执行此操作,然后按顺序排列它们的子级应该可以得到预期的结果。

 function a() { let list = [] $(".ul_list").each(function() { let temp = [] $(this).children().each(function() { let text = $(this).text() text.replace(/\\s\\s+/g, ' ') temp.push(text) }) list.push(temp) }) return list } console.log(a()) 

Or if you need a recursive implementation that can handle nested ul s inside of each other: 或者,如果您需要一个可以相互处理嵌套ul的递归实现:

 function getListItems(ul) { let temp = [] $(ul).children().each(function() { if ($(this).is("ul")) { // checks if child is a list temp.push(getListItems($(this))) // recursive call } else { // child is list item let text = $(this).text() text.replace(/\\s\\s+/g, ' ') temp.push(text) } }) return temp } function a() { // main function let list = [] $(".ul_list").each(function() { list.push(getListItems($(this))) }) return list } console.log(a()) 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <!DOCTYPE html> <html> <head> <title></title> <link rel="stylesheet" type="text/css" href="style.css"> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script> <script src=https://code.jquery.com/jquery-1.9.1.js></script> </head> <body> <ul class="ul_list"> <li>l1</li> <li>l2</li> <li>l3</li> <ul> <li>l1</li> <li>l2</li> <li>l3</li> <ul> <li>l1</li> <li>l2</li> <li>l3</li> <ul> <li>l1</li> <li>l2</li> <li>l3</li> </ul> </ul> </ul> </ul> <ul class="ul_list"> <li>l1</li> <li>l2</li> <li>l3</li> <ul> <li>l1</li> <li>l2</li> <li>l3</li> <ul> <li>l1</li> <li>l2</li> <li>l3</li> <ul> <li>l1</li> <li>l2</li> <li>l3</li> <ul> <li>l1</li> <li>l2</li> <li>l3</li> </ul> </ul> </ul> </ul> </ul> <ul class="ul_list"> <li>l1</li> <li>l2</li> <li>l3</li> </ul> <ul class="ul_list"> <li>l1</li> <li>l2</li> <li>l3</li> </ul> <ul class="ul_list"> <li>l1</li> <li>l2</li> <li>l3</li> </ul> <script type="text/javascript" src="main.js"></script> </body> </html> 

The following will map each ul to an array, and all the lis in each ul to an array, so it will be a 2 dimensional array, where each category_list[#] is a ul and the sub array is each li's text you modified. 以下内容将每个ul映射到一个数组,并将每个ul中的所有lis映射到一个数组,因此它将是一个二维数组,其中每个category_list[#]是一个ul,子数组是您修改的每个li的文本。

 function a() { var category_list = $('.ul_list').get().map(function(ul){ return $('li', ul).get().map(function(li){ return $(li).text().replace(/\\s\\s+/g, ' '); //removes whitespaces }); }); console.log(category_list); } a(); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <ul class="ul_list"> <li>1 Thing</li> <li>2 Thing</li> <li>3 Thing</li> </ul> <ul class="ul_list"> <li>4 Thing</li> <li>5 Thing</li> <li>6 Thing</li> </ul> 

Maybe a bit over simplified but I got the desired output. 也许有点简化,但我得到了期望的输出。
https://jsbin.com/tofimik/edit?html,js,console,output https://jsbin.com/tofimik/edit?html,js,console,output

Step 1. declare empty array 步骤1.声明空数组
Step 2. run your loop, get all children in your ul element 步骤2.运行循环,让所有子元素进入ul元素
Step 3. Turn each collection of children into an array 步骤3.将每个子级集合变成一个数组
Step 4. Push child collection into new array 步骤4.将子集合推入新数组

  var temp = []
  var cat;
  $('ul').each(function(){
    cat = []
    var liTags = Array($(this).children().text().trim());
    temp.push(liTags);
  })

(Posted the solution on behalf of the question author) . (代表问题作者发布了解决方案)

This solution was provided by James_F: 此解决方案由James_F提供:

   function a{
     let category_list = [];

     $(".ul_list").each(function(){
       let temp = [];
       $(this).children().each(function(){
          //adding only those list elements of a ul, that are red in color
          if($(this).children().attr("style") == "color:red"){
             var cat = $(this).text();
             cat = cat.replace(/\s\s+/g, ' '); //removes whitespaces
             temp.push(cat); //creates a single array for a single element
          }
       })
       category_list.push(temp);
     })
   }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM