从嵌套数组创建HTML元素

时间:2019-11-06 22:32:51

标签: javascript

我正在尝试创建餐厅菜单的移动视图。菜单本身存储在menu变量中,该变量以

的形式保存数据
let menu = [
  [
    'Food Section', //i.e Appetizers
    ['Entry', 'Food Description' , 'Price'],
    ['Entry', 'Food Description' , 'Price']

  ]
  [
    'Food Section', //i.e Soup
    ['Entry', 'Food Description' , 'Price'],
    ['Entry', 'Food Description' , 'Price']
  ],
   etc...

我希望网站本身显示带有食物部分的按钮(“开胃菜”按钮,“汤”按钮),并且在单击所述按钮后,相应的食物条目将下拉并显示。现在,我尝试仅在每个buttons下创建适当条目的divsbutton。我通过遍历menu然后遍历每个menu元素来做到这一点。这是我的代码: js:

let menu = [
  [
      'Appetizers',
      ['Fried Calamari', "", '$11.95'],
      ['Mussels', "Marinara, fra diavolo or bianco", '$12.95'],
      ['Calamari & Mussels', "Fra diavolo or marinara", '$12.95'],
      ['Hot Antipasto', "Two baked clams, two stuffed shells, two stuffed mushrooms, two fried shrimp & scallops in a seafood sauce", '$14.95'],
    ],
    [
      'Soups',
      ['Chicken Noodle','','$4.95'],
      ['Minestrone','','$4.95'],
      ['Lentil','','$5.95'],
      ['Pasta Fagioli','','$5.95'],
      ['Cheese Tortellini','','$6.95'],
    ]



//create html elements by looping through menu variable
      for(i = 0; i < menu.length; i++){
        for(j = 0; j < menu[i].length; j++){
          if(j == 0){
            foodSectionText = menu[i][j];
            let btn = document.createElement("BUTTON");
            btn.innerHTML = foodSectionText;
            document.body.appendChild(btn);      }
          else{
            menuEntry = menu[i][j];
            console.log(menuEntry);
            for(i = 0; i < menuEntry.length; i++){
              div = document.createElement("DIV");
              div.innerHTML = menuEntry[i];
              document.body.appendChild(div);
            }
          }
        }
      }

上面的代码将创建:

<button>Appetizers</button>
<div>Fried Calamari</div>
<div></div>
<div>$11.95</div>

但是随后抛出Uncaught TypeError: Cannot read property 'length' of undefined指向for(j = 0; j < menu[i].length; j++)。为什么第二项['Mussels', "Marinara, fra diavolo or bianco", '$12.95'](及所有后续项)未正确呈现?另外,如果您有关于如何清理此过程的任何建议,请随时分享,我觉得我打算以一种可怕的方式来实现这一点...

1 个答案:

答案 0 :(得分:1)

在第3个for循环中,您将重用同一循环计数器# Assuming your array is a uniq, uniq_idx, counts = np.unique(a, axis=0, return_index=True, return_counts=True) # to return the array you want new_arr = uniq[counts == 1] # The indices of non-unique rows a_idx = np.arange(a.shape[0]) # the indices of array a nuniq_idx = a_idx[np.in1d(a_idx, uniq_idx[counts==1], invert=True)] 。尝试使用其他变量名(在我的示例中,我使用的是#new_arr array([[2, 3, 4], [3, 2, 1], [3, 4, 5]]) # nuniq_idx array([0, 2])

i