给定一串偶数和奇数,找到哪个是唯一的偶数或唯一的奇数。

例子 :
detectOutlierValue(“ 2 4 7 8 10”); // => 2-第三个数字为奇数,其余数字为偶数

即使我已经将所有内容都转换为数字,为什么还需要再次解析int(evens)?

function detectOutlierValue(str) {
  //array of strings into array of numbers
  newArr = str.split(" ").map(x => parseInt(x))

  evens = newArr.filter(num => num % 2 === 0)
  odds = newArr.filter(num => num % 2 !== 0)

  //if the array of evens has just 1 item while the majority is odds, we want to return the position of that item from the original string.

  if (evens.length === 1) {
    return newArr.indexOf(parseInt(evens))
  } else {
    return newArr.indexOf(parseInt(odds))
  }
}

最佳答案

原因是evensodds不是numbers。它们是arrays。在这种情况下odds = [7]。因此,您parseInt([7])得到7。请参阅控制台中的赔率。您返回odds[0]evens[0]



function detectOutlierValue(str) {
  //array of strings into array of numbers
  newArr = str.split(" ").map(x => parseInt(x))

  evens = newArr.filter(num => num % 2 === 0)
  odds = newArr.filter(num => num % 2 !== 0)
  //if the array of evens has just 1 item while the majority is odds, we want to return the position of that item from the original string.

  if (evens.length === 1) {
    return newArr.indexOf(evens[0])
  } else {
    console.log("odds =",odds);
    return newArr.indexOf(odds[0])
  }
}
console.log(detectOutlierValue("2 4 7 8 10"))

关于javascript - 检测字符串数组中的离群值-VanillaJS和parseInt,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54637158/

10-09 06:54