JavaScript 如何创建一个包含非重复元素的数组

JavaScript 如何创建一个包含非重复元素的数组

在本文中,我们将学习如何在JavaScript中创建一个包含非重复元素的数组。

以下是生成一个包含 n非重复随机数 的数组的两种方法:

  • 使用do-while循环和includes()方法。
  • 使用set并检查其大小。

方法1:使用do-while循环和includes()方法

在这里,includes()函数检查数组中是否存在元素。

示例:

// You can take this value from user
const n = 5
 
// Initial empty array
const arr = [];
 
// Null check
if (n == 0) {
    console.log(null)
}
 
do {
    // Generating random number
    const randomNumber = Math
        .floor(Math.random() * 100) + 1
 
    // Pushing into the array only 
    // if the array does not contain it
    if (!arr.includes(randomNumber)) {
        arr.push(randomNumber);
    }
} 
while (arr.length < n);
 
// Printing the array elements
console.log(arr)

输出

[ 29, 36, 38, 83, 50 ]

时间复杂度:

O(n2)  

方法2:使用集合(set)并检查其大小

记住,集合(set)不允许重复元素。

示例:

// You can take this value from user
const n = 5
 
// Initial empty array
const arr = [];
 
// Null Check
if (n == 0) {
    console.log(null)
}
 
let randomnumbers = new Set, ans;
 
// We keep adding elements till
// size of set is equal to n 
while (randomnumbers.size < n) {
 
    // Generating random number 
    // and adding it
    randomnumbers.add(Math.floor(
        Math.random() * 100) + 1);
}
 
// Copying set elements into 
// the result array
ans = [...randomnumbers];
 
// Printing the array
console.log(ans)

输出

[ 41, 75, 57, 62, 92 ]

时间复杂度:

O(n)

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程