给出一串偶数和奇数,找到哪个是唯一的偶数还是唯一的奇数。
示例: 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))
}
}
答案 0 :(得分:0)
这是因为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])
}
}
答案 1 :(得分:0)
原因是evens
和odds
不是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"))