在 JavaScript 中比较和填充数组
javascriptweb developmentfront end technologyobject oriented programming更新于 2026/2/9 10:52:17
我们需要编写一个函数来比较两个数组并创建第三个数组,用第二个数组的所有元素填充该数组,并为第一个数组中存在但在第二个数组中遗漏的所有元素填充 null。
例如:
如果两个数组是 −
const arr1 = ['f', 'g', 'h']; const arr2 = ['f', 'h'];
那么输出应该是 −
const output = ['f', null, 'h'];
因此,让我们编写该函数的代码 −
示例
其代码为 −
const arr1 = ['f', 'g', 'h'];
const arr2 = ['f', 'h'];
const compareAndFill = (arr1, arr2) => {
let offset = 0;
const res = arr1.map((el, i) => {
if (el === arr2[offset + i]) {
return el;
};
offset--;
return null;
});
return res;
};
console.log(compareAndFill(arr1, arr2));
输出
控制台中的输出将是 −
[ 'f', null, 'h' ]
相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

