javascript - findTwins,它接受一个整数数组并找到两个相同的数字并返回重复两次的数字

标签 javascript object count

我遇到了一个错误,并且知道为什么“count”返回一个错误。请帮忙。

Write a function called findTwins, which accepts an array of integers and finds two of same numbers and returns the number that is repeated twice. The function should return null if there is not a number repeated twice.

function findTwins(arr) {
  if (arr.length === 0) return null;
  let count = {};
  //count occurances of each item
  for (let i = 0; i < arr.length; i++) {
    let num = arr[i];
    //if element isn't in given key, assign it value '0'
    if (count[num] === undefined) {
      count[num] = 0;
    } //if element has occured in object, increase it by 1
    count[num]++;
  }

  //iterate through count object   
  for (let key in count) {
    //if value of count is 2, returns that key
    if (count[key] === 2) {
      return key;

      //if there are no repeats in array, return null    
    } else {
      (count[key] === 0) {
        return null;
      }
    }
  }
}

console.log(
  findTwins([2, 3, 6, 34, 7, 8, 2]), // 2
  findTwins([]), // null
  findTwins([3, 1, 4, 2, 5]) // null
)

最佳答案

  • 您在 (count[key] === 0) {

  • 中缺少一个“if”
  • 您需要在函数末尾返回 null 以处理不匹配

  • 我不会使用数组的 for (let key in count) { - 有比对象遍历更安全和更好的方法来迭代数组

    <
  • Reduce 或 filter 是处理数组的更好方法:

这是一个基于 https://stackoverflow.com/a/35922651/295783 的解决方案

function findTwins(arr) {
  let ret = null;
  if (arr && arr.length) ret = arr.filter(function(value, index, self) {
    return (self.indexOf(value) !== index)
  })
  return !ret || ret.length == 0 ? null : ret;
}

console.log(
  findTwins([2, 3, 6, 34, 7, 8, 2]), // 2
  findTwins([]), // null
  findTwins([3, 1, 4, 2, 5]) // null
);

她是基于https://stackoverflow.com/a/54966920/295783中建议的版本

function findTwins(arr) {
  let res = [];
  if (arr && arr.length) {
    for (let i = 0; i < arr.length; i++) {
      var num = arr[i];
      if (arr.indexOf(num) !== arr.lastIndexOf(num) &&
          res.indexOf(num) === -1) res.push(num)
    }
  }
  return res.length ? res : null;
}


console.log(
  findTwins([2, 3, 6, 34, 7, 8, 2]), // 2
  findTwins([]), // null
  findTwins([3, 1, 4, 2, 5]), // null
  findTwins([3, 1, 2,5,4, 2, 5]) // null
)

关于javascript - findTwins,它接受一个整数数组并找到两个相同的数字并返回重复两次的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54966761/

相关文章:

javascript - 无法从事件处理程序访问 js 对象方法

MySQL 使用 JOIN 语句计算匹配行数

javascript - 如何定义一个构造函数来生成具有 getter 和 setter 的对象?

javascript - 将 javascript 函数应用于相同的 id

javascript - 如何检测 jQuery 中的复选框单击

javascript - D3 : What does the scale do when passed an axis?

javascript - JavaScript 中的对象,如何循环向对象添加键和值?

MySQL - 将计数函数的结果划分为从单独列派生的列

excel - 显示 Excel 工作表计数

javascript - 如何在对象映射中插入条件语句?