Home  >  Article  >  Web Front-end  >  How to determine whether arrays contain the same values ​​in es6

How to determine whether arrays contain the same values ​​in es6

青灯夜游
青灯夜游Original
2022-03-07 18:01:505239browse

Judgment method: 1. Convert the array to a Set collection, and use the size attribute to get the total number of Set elements, the syntax is "new Set(arr).size"; 2. Use the length attribute to get the total number of array elements; 3. Compare the total number of Set elements and the total number of array elements to see if they are equal. If they are not equal, they contain the same value, and vice versa.

How to determine whether arrays contain the same values ​​in es6

The operating environment of this tutorial: Windows 7 system, ECMAScript version 6, Dell G3 computer.

In es6, you can use Set to determine whether there are the same elements in the array.

ES6 provides a new data structure Set. The values ​​of the members in the Set are all unique and there are no duplicate elements.

Method to determine whether there are the same elements in the array:

  • Convert the array to a Set and use the size attribute to return the total number of elements in the current Set

  • Judge whether the total number of Set elements is equal to the total number of array elements

let arr = [1,2,3,4,5];
if(new Set(arr).size !== arr.length){
  console.log("有相同的元素--------Yes");
} else {
    console.log("没有相同的元素------No");
}

How to determine whether arrays contain the same values ​​in es6

[Related recommendations: javascript video tutorialweb front-end

The above is the detailed content of How to determine whether arrays contain the same values ​​in es6. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn