输入:array = [2,5,1,2,3,5,1,2,4]
输出返回2
输入:array = [2,1,1,2,3,5,1,2,4]
输出返回1
输入数组= [2,3,4,5]
输出返回未定义
我在repl.it上运行代码,并且始终返回未定义的代码。
有什么改进的方法可以使不确定的消失?
还如何在第三个输入中返回undefined?
我在JS中尝试的方式:
function FirstRecurringCharacter(arr){
for (i = 0; i < arr.length; i++) {
if (arr.indexOf(arr[i]) !== i) {
console.log(arr[i]);
break;
}
}
};
FirstRecurringCharacter([2,5,1,2,3,5,1,2,4])//should return 2
FirstRecurringCharacter([2,1,1,2,3,5,1,2,4])//should return 1
FirstRecurringCharacter([2,3,4,5])//should rerturn undefined
答案 0 :(得分:5)
您可以使用Set
并使用Array#find
。
function find(array) {
var s = new Set;
return array.find(v => s.has(v) || !s.add(v));
}
console.log(find([2, 5, 1, 2, 3, 5, 1, 2, 4])); // 2
console.log(find([2, 1, 1, 2, 3, 5, 1, 2, 4])); // 1
console.log(find([2, 3, 4, 5])); // undefined
答案 1 :(得分:2)
您应该返回该值,而不是登录到控制台。
function FirstRecurringCharacter(arr){
for (i = 0; i < arr.length; i++) {
if (arr.indexOf(arr[i]) !== i) {
return arr[i];
}
}
return undefined;
};
console.log(FirstRecurringCharacter([2,5,1,2,3,5,1,2,4]))//should return 2
console.log(FirstRecurringCharacter([2,1,1,2,3,5,1,2,4]))//should return 1
console.log(FirstRecurringCharacter([2,3,4,5]))//should rerturn undefined
答案 2 :(得分:0)
function firstReccuringChar(arr) {
let map = {};
for (let i = 0; i < arr.length; i++) {
if (map[arr[i]] !== undefined) {
return arr[i];
} else {
map[arr[i]] = i;
}
console.log(map);
}
return undefined;
}
console.log(firstReccuringChar([2, 5, 1, 2, 3, 5, 1, 2, 4]));
//使用哈希表或对象的另一个示例。
答案 3 :(得分:0)
function firstRecurringCharacter(input) {
let result = {};
let len = input.length;
for (let i = 0; i < len; i++) {
if (result[input[i]] !== undefined) {
return input[i];
} else {
result[input[i]] = i;
}
}
return undefined;
}