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

标签 javascript multidimensional-array ecmascript-6 count repeat

问题

我不确定我在这里做错了什么。我正在做一个coding challenge on CodeFights使用普通 JavaScript 查找并返回数组中的第一个重复元素。我的代码适用于 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

我的问题

我知道我的代码大部分是正确的,那么我缺少什么/或者我放错了什么地方?如何让“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

关于JavaScript 编码面试数组中的第一个重复字符不适用于 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50711835/

相关文章:

javascript - 找到一个 jquery 元素,其父元素包含一些文本

javascript - 数据列表垂直滚动在 Chrome 中不起作用

c++ - 如何正确删除多维 vector ?

python - Numpy ndarray 按行对值进行排序,然后排除索引

c - 在 C 中初始化 3 维字符数组

javascript - babel/register 未在服务器上运行

javascript - 在 ReactJS 的列表中连接更多项目时保持滚动位置

javascript - 数据表未格式化日期时间

javascript - 在事件监听器中使用 .replace() 更改某些文本,无法使其工作

javascript - Electron 预加载函数而不是外部文件?