尝试更改不使用 null 的条件

Trying to Change The Condition of without using null

我正在尝试在下面的代码中检查重复项并将项目推送到数组中,该功能运行良好,但是除了使用 null 之外还有其他方法可以做到这一点

array2.forEach((item) =>
   array1.includes(item)
 ? null
 : array1.push(item),
);

可以使用&&短路操作

const array1 = [1, 2, 3, 4, 5, 6],
  array2 = [4, 5, 6, 7, 8, 9, 10];
array2.forEach((item) => !array1.includes(item) && array1.push(item));
console.log(array1)

你可以用一套

const set = new Set();
const brr = ["one","one"].forEach(item=> set.add(item));
Array.from(set) 
// --> ["one"]

您可以使用扩展运算符 (...) 和 Set

等 ES6 功能

let array1 = [1,2,3,4,5,6];
let array2 = [4,5,6,7,8,9,10];
const mergedArrays = [...array1, ...array2];
array1 = [...new Set(mergedArrays)];    // make the array elements unique
console.log(array1);

这应该有效:

array1.push( ... array2.filter(item => !array1.includes(item) ) )

或者您可以将 arrays 切换为 Set() 并使用:

array2.forEach( item => array1.add(item) )

你可以使用“undefined”而不是“null”,undefined 意味着什么都不做,而 null 本身就是一个值。

ar

ray2.forEach((item) =>
   array1.includes(item)
 ? undefined
 : array1.push(item),
);