防止在 JavaScript 中向数组添加重复项

防止向数组添加重复项

Prevent adding Duplicates to an Array in JavaScript

要防止向数组添加重复项:

  1. 使用该Array.includes()方法检查数组中是否不存在该值。
  2. 如果该值不存在,请使用push()方法将其添加到数组中。
  3. 该数组将不包含任何重复值。
索引.js
const arr = ['apple', 'pear', 'mango']; const str = 'apple'; if (!arr.includes(str)) { // ✅ only runs if value not in array arr.push(str); } console.log(arr); // 👉️ ['apple', 'pear', 'mango']

我们传递给
Array.includes
方法的唯一参数是要在数组中搜索的值。

includes()方法返回一个布尔结果:

  • true如果该值存在于数组中
  • false如果不是

We used the
logical NOT (!)
operator to negate the call to the includes() method because we want to add
the value only if it isn’t already present in the array.

Here are some more examples of using the logical NOT (!) operator.

index.js
console.log(!true); // 👉️ false console.log(!false); // 👉️ true console.log(!'hello'); // 👉️ false console.log(!''); // 👉️ true console.log(!null); // 👉️ true

You can imagine that the logical NOT (!) operator first converts the value to a
boolean and then flips it.

When you negate a falsy value, the operator returns true, in all other cases it returns false.

Falsy values are: null, undefined, empty string, NaN, 0 and false.

Prevent adding Duplicates to an Array using indexOf #

To prevent adding duplicates to an array:

  1. Use the indexOf() method to check that the value is not present in the
    array.
  2. The indexOf method returns -1 if the value is not contained in the array.
  3. If the condition is met, push the value to the array.
index.js
const arr = ['apple', 'pear', 'mango']; const str = 'apple'; if (arr.indexOf(str) === -1) { arr.push(str); } console.log(arr); // 👉️ ['apple', 'pear', 'mango']

The
Array.indexOf
method returns the index of the first occurrence of the value in the array.

If the value is not present in the array, it returns -1.

The if statement checks if the indexOf method returned -1. If it did, the value is not present in the array, so we use the push() method.

An alternative approach is to use a
Set
object, instead of an array.

Set objects store a collection of unique values. This makes it impossible to add
a duplicate value to a Set.

index.js
const str = 'apple'; const set1 = new Set(['apple', 'pear', 'mango']); set1.add(str); console.log(set1); // 👉️ {'apple', 'pear', 'mango'}

We used the
Set.add
method to add a value to the Set.

该值已包含在 中Set,因此我们对该add方法的调用没有执行任何操作。

Set 对象比数组更受限制,实现的方法也更少。但是,它们有自己的用例,存储唯一值是主要的用例。