javascript - 检测字符串数组中的异常值 - VanillaJS 和 parseInt

标签 javascript parseint

给定一串偶数和奇数,找出唯一的偶数或唯一的奇数。

示例: 检测离群值(“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 在您将它们放入 indexOf 时是数组。尝试用每个数组的第一个值替换最后两行:

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 {
    return newArr.indexOf(odds[0]) 
  }
}

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

相关文章:

java - 从输入流读取的 csv 文件解析数组的第一项时出现问题

javascript - 使用 CSS 和 JS 设置 SVG 样式

javascript - 如何隐藏高级元素?

javascript - 将数字传递给新生成的数组时无法设置未定义的属性

javascript - 在输入字段上使用 parseInt 不起作用

javascript - ParseInt() 奇怪的八进制行为

java - java中如何将多个字符串解析为int

JavaScript for 循环与 jquery 不起作用

javascript - 如何使用纯 JS 通过 AJAX 获取文件夹中的所有图像?

java - 在 Java 中,如何检查输入是否为数字?