javascript - 这段代码如何在数组中搜索多个值?

标签 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;

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

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

最佳答案

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

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;

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

关于javascript - 这段代码如何在数组中搜索多个值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53349545/

相关文章:

kotlin - 如何在Kotlin中替换长链的forEach {}语句?

javascript - onClick Div 选中未选中复选框

javascript - javascript中命名函数和匿名函数的原型(prototype)结构有何区别?

javascript - jQuery 在 Wordpress 中不工作

javascript - 从字符串中删除字符并返回包含删除字符的新字符串

javascript - 通过 ES6 中的项键减少数组

javascript - 如何从映射的多个复选框中选择一个复选框 React.js

javascript - forEach在javascript中同时遍历两个数组

python - 使用 numpy 将图像转换为灰度

jQuery 为每个附加子节点