JavaScript 中数组中出现两次的元素
javascriptweb developmentfront end technologyobject oriented programming更新于 2024/1/5 19:56:17
我们需要编写一个 JavaScript 函数,该函数接受一个文字值数组。我们的函数应该从数组中挑选所有在数组中恰好出现两次的值,并返回这些元素的新数组。
示例
其代码为 −
const arr = [0, 1, 2, 2, 3, 3, 5];
const findAppearances = (arr, num) => {
let count = 0;
for(let i = 0; i < arr.length; i++){
const el = arr[i];
if(num !== el){
continue;
};
count++;
};
return count;
};
const pickAppearingTwice = (arr = []) => {
const res = [];
for(let i = 0; i < arr.length; i++){
const el = arr[i];
if(findAppearances(arr, el) === 2 && !res.includes(el)){
res.push(el);
};
};
return res;
};
console.log(pickAppearingTwice(arr));
输出
控制台中的输出将是 −
[2, 3]
相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

