我遇到了一个错误,并且知道为什么“count”返回一个错误。请帮忙。
Write a function called findTwins, which accepts an array of integers and finds two of same numbers and returns the number that is repeated twice. The function should return null if there is not a number repeated twice.
function findTwins(arr) {
if (arr.length === 0) return null;
let count = {};
//count occurances of each item
for (let i = 0; i < arr.length; i++) {
let num = arr[i];
//if element isn't in given key, assign it value '0'
if (count[num] === undefined) {
count[num] = 0;
} //if element has occured in object, increase it by 1
count[num]++;
}
//iterate through count object
for (let key in count) {
//if value of count is 2, returns that key
if (count[key] === 2) {
return key;
//if there are no repeats in array, return null
} else {
(count[key] === 0) {
return null;
}
}
}
}
console.log(
findTwins([2, 3, 6, 34, 7, 8, 2]), // 2
findTwins([]), // null
findTwins([3, 1, 4, 2, 5]) // null
)
最佳答案
您在
(count[key] === 0) {
中缺少一个“if”
您需要在函数末尾
返回 null
以处理不匹配我不会使用数组的
<for (let key in count) {
- 有比对象遍历更安全和更好的方法来迭代数组Reduce 或 filter 是处理数组的更好方法:
这是一个基于 https://stackoverflow.com/a/35922651/295783 的解决方案
function findTwins(arr) {
let ret = null;
if (arr && arr.length) ret = arr.filter(function(value, index, self) {
return (self.indexOf(value) !== index)
})
return !ret || ret.length == 0 ? null : ret;
}
console.log(
findTwins([2, 3, 6, 34, 7, 8, 2]), // 2
findTwins([]), // null
findTwins([3, 1, 4, 2, 5]) // null
);
她是基于https://stackoverflow.com/a/54966920/295783中建议的版本
function findTwins(arr) {
let res = [];
if (arr && arr.length) {
for (let i = 0; i < arr.length; i++) {
var num = arr[i];
if (arr.indexOf(num) !== arr.lastIndexOf(num) &&
res.indexOf(num) === -1) res.push(num)
}
}
return res.length ? res : null;
}
console.log(
findTwins([2, 3, 6, 34, 7, 8, 2]), // 2
findTwins([]), // null
findTwins([3, 1, 4, 2, 5]), // null
findTwins([3, 1, 2,5,4, 2, 5]) // null
)
关于javascript - findTwins,它接受一个整数数组并找到两个相同的数字并返回重复两次的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54966761/