在 JavaScript 中从多个数组中获取公共元素
javascriptweb developmentfront end technologyobject oriented programming更新于 2026/2/8 22:04:17
我们需要编写一个 JavaScript 函数,该函数接受任意数量的数组并返回所有数组共有的元素数组。如果没有公共元素, 那么我们应该返回一个空数组。
因此,让我们编写该函数的代码 −
示例
其代码为 −
const arr1 = [2, 6, 7, 1, 7, 8, 4, 3];
const arr2 = [5, ,7, 2, 2, 1, 3];
const arr3 = [1, 56, 345, 6, 54, 2, 68, 85, 3];
const intersection = (arr1, arr2) => {
const res = [];
for(let i = 0; i < arr1.length; i++){
if(!arr2.includes(arr1[i])){
continue;
};
res.push(arr1[i]);
};
return res;
};
const intersectMany = (...arrs) => {
let res = arrs[0].slice();
for(let i = 1; i < arrs.length; i++){
res = intersection(res, arrs[i]);
};
return res;
};
console.log(intersectMany(arr1, arr2, arr3));
输出
控制台中的输出将是 −
[2, 1, 3]
相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

