用 JavaScript 找出两个数字数组中不同元素
我们需要编写一个 JavaScript 函数,输入数字数组后输出数组中那些不属于两者的元素。
例如,如果两个数组为 -
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 ]
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP