在 JavaScript 中查找两个 Number 数组中的偏差
javascriptweb developmentfront end technologyobject oriented programming更新于 2026/1/25 5:00:17
我们需要编写一个 JavaScript 函数,该函数接受 Number 数组并返回两个数组中不相同的元素。
例如,如果两个数组是 −
const arr1 = [2, 4, 2, 4, 6, 4, 3]; const arr2 = [4, 2, 5, 12, 4, 1, 3, 34];
输出
那么输出应该是 −
const output = [ 6, 5, 12, 1, 34 ]
示例
其代码为 −
const arr1 = [2, 4, 2, 4, 6, 4, 3];
const arr2 = [4, 2, 5, 12, 4, 1, 3, 34];
const deviations = (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(deviations(arr1, arr2));
输出
控制台中的输出 −
[6, 5, 12, 1, 34 ]
相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

