如何优化长 if 语句并编写更好的代码?

How can I optimise long if statements and make better code?

我正在学习 JS,我想制作自己的小应用程序,我可以在数组中存储许多随机的唯一数字。我的 代码工作正常,但我想制作很多数组,但我遇到了大 if 条件的问题,例如:

if ( !num[0].includes(number) && !num[1].includes(number) && !num[2].includes(number) && !num[3].includes(number) )

我花了一些时间搜索类似的示例,但不知道如何优化我的代码。我怎样才能使我的代码更好? 提前致谢:-)

const nums = [];
const N = 4;
for(let i=0; i<N; i++){
    nums[i] = [];
}
const uniqueNumber = function(minValue, maxValue){
    const number = Math.floor(Math.random()*(maxValue-minValue+1)+minValue);
    if (!nums[0].includes(number)) {
        nums[0].push(number);
        return number;
    } else if (nums[0].length - 1 !== maxValue) {
        uniqueNumber(minValue, maxValue);
    }
}
const uniqueNumber_2 = function(minValue, maxValue){
    const number = Math.floor(Math.random()*(maxValue-minValue+1)+minValue);
    if ( !nums[0].includes(number) && !nums[1].includes(number) ) {
        nums[1].push(number);
        return number;
    } else if (nums[1].length - 1 !== maxValue) {
        uniqueNumber_2(minValue, maxValue);
    }
}
const uniqueNumber_3 = function(minValue, maxValue){
    const number = Math.floor(Math.random()*(maxValue-minValue+1)+minValue);
    if ( !nums[0].includes(number) && !nums[1].includes(number) && !nums[2].includes(number) ) {
        nums[2].push(number);
        return number;
    } else if (nums[2].length - 1 !== maxValue) {
        uniqueNumber_3(minValue, maxValue);
    }
}
const uniqueNumber_4 = function(minValue, maxValue){
    const number = Math.floor(Math.random()*(maxValue-minValue+1)+minValue);
    if ( !nums[0].includes(number) && !nums[1].includes(number) && !nums[2].includes(number) && !nums[3].includes(number) ) {
        nums[3].push(number);
        return number;
    } else if (nums[3].length - 1 !== maxValue) {
        uniqueNumber_4(minValue, maxValue);
    }
}
const min = 10;
const max = 90;
const howMany = (max-min)/N;
for(let i=0; i<howMany; i++){
    uniqueNumber(min, max);
}
for(let i=0; i<howMany; i++){
    uniqueNumber_2(min, max);
}
for(let i=0; i<howMany; i++){
    uniqueNumber_3(min, max);
}
for(let i=0; i<howMany; i++){
    uniqueNumber_4(min, max);
}
const numsH2 = [];
for(let i=0; i<N; i++){
    numsH2[i] = "<h2>Array " + i + "</h2>";
}
for(let i=0; i<N; i++){
    if(i == N-1){
        document.getElementById("pNumbers").innerHTML +=  numsH2[i] + nums[i] + "<br>";
    } else {
        document.getElementById("pNumbers").innerHTML += numsH2[i] + nums[i] + "<br><br><hr><br>";
    }
}
*{
    margin: 0;
    padding: 0;
}
*, *::before, *::after{
    box-sizing: border-box;
}
body {
    display: flex;
    flex-direction: column;
    align-items: center;
    word-wrap: break-word;
    font-family: "Courier New",monospace;
}
#numbers{
    width: 443px;
    margin-top: 60px;
}
#numbers h1{
    font-size: 18px;
    text-align: center;
    padding-bottom: 20px;
}
#numbers p{
    padding: 7px;
    font-size: 14px;
}
#numbers h2{
    font-size: 14px;
    padding-bottom: 5px;
}
#pNumbers {
    background: rgb(235 249 255);
}
hr{
    width: 100%;
    height: 1px;
    margin-left: auto;
    margin-right: auto;
    background-color: #b7d0e2;
    border: 0 none;
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Random arrays</title>
    <link rel="stylesheet" href="./css/style.css">
</head>
<body>
    <div id="numbers">
        <h1>Unique numbers in Arrays</h1>
        <p id="pNumbers"></p>
    </div>
    <script src="./js/script.js"></script>
</body>
</html>

通过使第三个参数指示最多搜索多少个索引来概括该函数。然后你可以 .slice nums 数组提取所有子数组进行检查,如果它们通过 .every 测试,则推到最后一个。

const uniqueNumber = function (minValue, maxValue, maxSubarrayIndex) {
    const number = Math.floor(Math.random() * (maxValue - minValue + 1) + minValue);
    const subarrays = nums.slice(0, maxSubarrayIndex + 1);
    if (subarrays.every(subarr => !subarr.includes(number))) {
        nums[maxSubarrayIndex].push(number);
    } else {
        uniqueNumber(minValue, maxValue, maxSubarrayIndex);
    }
}

这可以取代所有的功能,例如代替

uniqueNumber_3(2, 5)

你可以做到

uniqueNumber(2, 5, 3)

编写函数

包含范围内的随机整数

首先,让我们把那个inclusive bounds random number计算放到它自己的函数中。

const getRandomInt = (min, max) =>
    Math.floor(Math.random() * (max - min + 1)) + min;

唯一编号集

接下来,让我们利用 Set 来避免所有 “我有这些之一吗” 检查来创建随机数数组。只需不断将随机数添加到您的集合中,直到它具有所需数量的元素。 Set 可以 spread 回到 Array。 注意,此版本不会尝试避免无限循环或防止无效参数,例如 N 为零时发生的情况。

const uniqueNumbers = (min, max, N) => {
  const howMany = (max - min) / N;
  const set = new Set();
  while (set.size < howMany) set.add(getRandomInt(min, max));
  return [...set];
}

N 个事物的数组

最后,您需要一种方法来制作 n 事物的数组,其中事物由函数定义。 numerous ways of accomplishing this, but Array.from 几乎正是你所需要的,你只需要向它传递一个定义了 length 属性.

的对象
const arrayOfN = (length, fn) => Array.from({ length }, fn);

使用你的函数

有了这 3 件事,您就可以更简洁地编写代码来生成一个由 4 组这样的唯一数字组成的数组。

const min = 10;
const max = 90;
const N = 4;
const nums = arrayOfN(4, () => uniqueNumbers(min, max, N));

下面的工作示例:

const getRandomInt = (min, max) =>
    Math.floor(Math.random() * (max - min + 1)) + min;

const uniqueNumbers = (min, max, N) => {
  const howMany = (max - min) / N;
  const set = new Set();
  while (set.size < howMany) set.add(getRandomInt(min, max));
  return [...set];
}

const arrayOfN = (length, fn) => Array.from({ length }, fn);

const min = 10;
const max = 90;
const N = 4;
const nums = arrayOfN(4, () => uniqueNumbers(min, max, N));

console.log(nums);