用于查找两个数组中不常见元素的程序 - JavaScript
javascriptweb developmentfront end technologyobject oriented programming更新于 2025/11/24 19:56:17
假设我们有两个数字数组 −
const arr1 = [12, 54, 2, 4, 6, 34, 3]; const arr2 = [54, 2, 5, 12, 4, 1, 3, 34];
我们需要编写一个 JavaScript 函数,该函数接受两个这样的数组并返回两个数组中不常见的元素。
让我们来编写该函数的代码 −
示例
以下是代码 −
const arr1 = [12, 54, 2, 4, 6, 34, 3];
const arr2 = [54, 2, 5, 12, 4, 1, 3, 34];
const unCommonArray = (first, second) => {
const res = [];
for(let i = 0; i < first.length; i++){
if(second.indexOf(first[i]) === -1){
res.push(first[i]);
}
};
for(let j = 0; j < second.length; j++){
if(first.indexOf(second[j]) === -1){
res.push(second[j]);
};
};
return res;
};
console.log(unCommonArray(arr1, arr2));
输出
以下是控制台中的输出 −
[ 6, 5, 1 ]
相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

