检测字符串数组中的离群值-VanillaJS和parseInt

时间:2019-02-11 18:47:46

标签: javascript parseint

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

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

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

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)) 
  }
}

2 个答案:

答案 0 :(得分:0)

这是因为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]) 
  }
}

答案 1 :(得分:0)

原因是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"))