JavaScript 编码面试数组中的第一个重复字符不适用于 null

JavaScript coding interview first repeating character in array not working for null

问题

我不确定我做错了什么。我正在做一个 coding challenge on CodeFights 使用 vanilla JavaScript 来查找和 return 数组中的第一个重复元素。我的代码适用于 2 个测试数组(ac),但 不适用于没有重复元素的情况 .

我的代码

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

我的问题

我知道我的代码大部分都是正确的,所以我 missing/or 我是不是放错了什么地方?我怎样才能使 "null" 案例起作用(当没有重复字符时)。

您想在每次调用 firstDuplicate 时重置 counts。否则每次调用将共享同一个对象。

您还在 for 循环中引用了 a,但应该引用 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