此代码如何在数组中搜索多个值?

时间:2018-11-17 08:27:31

标签: javascript arrays foreach duplicates

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

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;

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

这是怎么回事?有人可以逐行解释。我是JavaScript新手。

2 个答案:

答案 0 :(得分:2)

这是代码,每行都有注释!希望对您有所帮助;)

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;

如果不设置花括号,将仅执行下一条指令!

答案 1 :(得分:1)

也许您错过了block statement { ... }中的if statement,而

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

这意味着,如果object[item]不是truthy,则将零分配给object[item]

然后增加此值。

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

给定的代码是对上述代码的有效更改,只需采用一条语句即可,用分号结束。在这种情况下,您不需要阻塞语句。