代码之家  ›  专栏  ›  技术社区  ›  billy

在一个数组中搜索多个值的代码是如何工作的?

  •  1
  • billy  · 技术社区  · 6 年前

    我正在寻找一种在数组中查找多个值的解决方案,并发现:

    function find_duplicate_in_array(arra1) {
      var object = {};
      var result = [];
    
      arra1.forEach(function(item) {
        if (!object[item])
          object[item] = 0;
        object[item] += 1;
      })
    
      for (var prop in object) {
        if (object[prop] >= 2) {
          result.push(prop);
        }
      }
      return result;
    }
    
    console.log(find_duplicate_in_array([1, 2, -2, 4, 5, 4, 7, 8, 7, 7, 71, 3, 6]));

    我不明白发生了什么事。具体而言:

    object[item] = 0;
    object[item] +=1;
    

    所以对于数组中的每个元素,如果该元素不在 暂时的 对象在索引0处添加元素,然后再添加+1?。

    发生什么事?请有人逐行解释一下好吗。我是JavaScript新手。

    2 回复  |  直到 6 年前
        1
  •  2
  •   sjahan    6 年前

    下面是代码,每行都有注释!我希望它能帮助你;)

    function find_duplicate_in_array(arra1) {
    
      // Temporary count of each item in the input array/
      var object = {};
      // Final result containing each item that has been seen more than one time.
      var result = [];
    
      // For each item of the array...
      arra1.forEach(function (item) {
        // If it is not in the temporary object, initialize it to 0.
        if(!object[item])
          object[item] = 0;
        // Add one since we just have found it!  
        object[item] += 1;
      })
    
    
      // Now, every item of the input array has been counted in object.
      // For each item of object:
      for (var prop in object) {
        // If it has been counted more than one time, add it to the result.
        if(object[prop] >= 2) {
          result.push(prop);
        }
      }
    
      // Return the result.
      return result;
    
    }
    
    console.log(find_duplicate_in_array([1, 2, -2, 4, 5, 4, 7, 8, 7, 7, 71, 3, 6]));

    复杂性 以下是这些方面的信息:

    if(!object[item])
      object[item] = 0;
    object[item] += 1;
    

    它与更严格的符号相同:

    if(!object[item]) {
      object[item] = 0;
    }
    object[item] += 1;
    

    如果不设置大括号,则只执行下一条指令!

        2
  •  1
  •   Nina Scholz    6 年前

    也许你错过了机会 block statement { ... } if statement

    if (!object[item]) {
        object[item] = 0;
    }
    object[item] += 1;
    

    object[item] 不是 truthy 对象[项目] .

    if (!object[item])    // no block statement
        object[item] = 0; // then part finished with semicolon
    object[item] += 1;    // code after the condition
    

    给定的代码是对上述内容的有效更改,只接受一条语句,该语句以分号结尾。在这种情况下,不需要block语句。