我不确定我在这里做错了什么。我正在使用vanilla JavaScript进行coding challenge on CodeFights查找并返回数组中的第一个重复元素。我的代码适用于2个测试数组(a
和c
)但不适用于没有重复元素的情况。
console.clear();
var a = [2, 1, 3, 5, 3, 2];
var b = [2, 4, 3, 5, 1];
var c = ["apple", "orange", "grape", "orange", "grape"];
// create an object to store the counts
var counts = {};
function firstDuplicate(arr) {
// loop through passed array of numbers
for (var i=0; i<a.length; i++) {
var num = arr[i];
if (counts[num] === undefined) {
counts[num] = 1;
} else if (counts[num] == 1) {
++counts[num];
return num;
}
}
return -1;
}
console.log(firstDuplicate(a)); // 3
console.log(firstDuplicate(b)); // -1
console.log(firstDuplicate(c)); // orange
&#13;
我知道我的代码大部分是正确的,所以我错过了什么/或者我放错了什么?我怎样才能获得&#34; null&#34;工作的情况(当没有重复的字符时)。
答案 0 :(得分:2)
您希望每次调用counts
时重置firstDuplicate
。否则,每个调用都将共享同一个对象。
您也在a
循环中引用for
,但应该引用arr
函数参数。
var a = [2, 1, 3, 5, 3, 2];
var b = [2, 4, 3, 5, 1];
var c = ["apple", "orange", "grape", "orange", "grape"];
function firstDuplicate(arr) {
// move this definition inside the function so that each
// time you call firstDuplicate() you get a new counts object.
var counts = {};
// use arr.length so that you are iterating through the arr parameter
for (var i=0; i<arr.length; i++) {
var num = arr[i];
if (counts[num] === undefined) {
counts[num] = 1;
} else if (counts[num] == 1) {
++counts[num];
return num;
}
}
return -1;
}
console.log(firstDuplicate(a)); // 3
console.log(firstDuplicate(b)); // -1
console.log(firstDuplicate(c)); // orange