嵌套数组的Javascript表示问题

时间:2017-02-13 08:36:51

标签: javascript arrays for-loop nested-loops

我有两个与两个元素相交的数组,如下所示。通常这个函数应写成A,B,Y但它代表所有值lista.length * listb.length

<script>
    window.onload = function(){     
        var lista = [];
        lista[0] = "A";
        lista[1] = "B";
        lista[2] = "Y";

        var listb = [];
        listb[0] = "A";
        listb[1] = "B";

        for(var i=0; i<lista.length; i++){
            for(var j=0; j<listb.length; j++){
                if(listb[j] == lista[i]){
                    document.write(listb[j] + "<br/>");
                }else{
                    document.write(lista[i] + "<br/>");                 
                }               
            }
        }
    }
</script>

3 个答案:

答案 0 :(得分:2)

您只能打印外循环的元素

&#13;
&#13;
window.onload = function() {
    var lista = ["A", "B", "Y"],
        listb = ["A", "B"];

    for (var i = 0; i < lista.length; i++) {
        document.write(lista[i]);
        for (var j = 0; j < listb.length; j++) {
            if (listb[j] == lista[i]) {
                document.write(" common");
                break;
            }
        }
        document.write("<br/>");
    }
}
&#13;
&#13;
&#13;

答案 1 :(得分:2)

您需要等到内循环结束才知道是否找到了匹配项,而不是为每个不匹配的元素打印lista[i]

    for(var i=0; i<lista.length; i++){
        for(var j=0; j<listb.length; j++){
            var found = false;
            if(listb[j] == lista[i]){
                document.write(listb[j] + "<br/>");
                found = true;
                break;
            }
            if (!found){
                document.write(lista[i] + "<br/>");                              
            }
        }
    }

答案 2 :(得分:1)

试试这个

 <script>
        window.onload = function(){     
          var lista = [];
          lista[0] = "A";
          lista[1] = "B";
          lista[2] = "Y";
    
          var listb = [];
          listb[0] = "A";
          listb[1] = "B";
    
          for(var i=0; i<lista.length; i++){
            for(var j=0; j<listb.length; j++){
              if(lista[i] == listb[j]){
                 document.write(listb[j] + "<br/>");
                break
              }else{
                 document.write(lista[i] + "<br/>");                 
                break
              }               
            }
          }
        }

  </script>