给定一串偶数和奇数,找出唯一的偶数或唯一的奇数。
示例: 检测离群值(“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))
}
}
最佳答案
这是因为 evens
和 odds
在您将它们放入 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/