代码之家  ›  专栏  ›  技术社区  ›  Razvan Cuceu

Javascript数组显示两次

  •  1
  • Razvan Cuceu  · 技术社区  · 7 年前

    我试图显示从复选框中选择的过滤器。首先,我创建一个从复选框中选择的值数组,并尝试将其附加到字符串中

    例如,我有两个复选框标记: label1 label2 ['label1','label2'] .

    预期结果将是“ Filtered by: Label1, Label2 Filtered by: Label1,Label2, Label1,Label2

    我想这是在for循环中我试图构建字符串的地方,因为数组看起来很好

    let topLabel = jQuery('.industry-filter').data('selected-text') + ' ';
    let termsName= ['Industry', 'Category']
    if(termsName.length){
      for(var j = 0; j < termsName.length; j++){
        if(j == termsName.length - 1){
          topLabel += termsName;
        }else{
          topLabel += termsName+', ';
        }
      }
    }else{
      topLabel = jQuery('.industry-filter').data('text');
    }
    
    $('.industry-filter').text(topLabel);
    

    这是一支显示问题的钢笔: https://codepen.io/anon/pen/pqjYxL

    2 回复  |  直到 7 年前
        1
  •  0
  •   Mihai Alexandru-Ionut    7 年前

    您应该通过其属性访问一个元素 指数

    if(j == termsName.length - 1){
      topLabel += termsName[j];
    }else{
      topLabel += termsName[j]+', ';
    }
    

    join 方法。

    if(termsName.length){
       topLabel += termsName.join(',')
    }
    
        2
  •  1
  •   Code Maniac    7 年前

    let topLabel = jQuery('.industry-filter').data('selected-text') + ' ';
    let termsName= ['Industry', 'Category']
    if(termsName.length){
      for(var j = 0; j < termsName.length; j++){
        if(j == termsName.length - 1){
          topLabel += termsName[j];
                               ^^^
        }else{
          topLabel += termsName[j] +', ';
                               ^^^
        }
      }
    }else{
      topLabel = jQuery('.industry-filter').data('text');
    }
    
    $('.industry-filter').text(topLabel);