如何在 JavaScript 数组中获得所有唯一值?
以下是在 JavaScript 数组中获取所有唯一值的代码 −
示例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
body {
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
}
.result,
.sample {
font-size: 18px;
font-weight: 500;
color: rebeccapurple;
}
.result {
color: red;
}
</style>
</head>
<body>
<h1>Get all unique values in a array</h1>
<div class="sample"></div>
<div class="result"></div>
<button class="Btn">Click here</button>
<h3>Click on the above button to remove the duplicate values from the above
array</h3>
<script>
let resultEle = document.querySelector(".result");
let sampleEle = document.querySelector(".sample");
let arr = [2, 3, 4, 2, 3, 4, "A", "A", "B", "B"];
sampleEle.innerHTML = "arr = " + arr;
document.querySelector(".Btn").addEventListener("click", () => {
let set1 = new Set(arr);
resultEle.innerHTML = "arr = " + [...set1] + "<br>";
});
</script>
</body>
</html>输出

点击“单击此处”按钮后 −

广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP