简体   繁体   English

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

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

I'm learning JS and I want make my own small app where I store many random unique numbers in arrays. My code works fine but I want to make many arrays and I have problems with big if conditionals for example:我正在学习 JS,我想制作自己的小应用程序,其中我在 arrays 中存储了许多随机的唯一数字。我的代码工作正常,但我想制作许多 arrays 并且我遇到了大 if 条件的问题,例如:

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

I spent some time searching similar examples and couldn't figure out how to optimise my code.我花了一些时间搜索类似的示例,但无法弄清楚如何优化我的代码。 How can I make my code better?我怎样才能使我的代码更好? Thanks in advance:-)提前致谢:-)

 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>

Generalize the function by making a third parameter indicating how many indicies to search up to.通过使第三个参数指示最多搜索多少个索引来概括 function。 Then you can .slice the nums array to extract all subarrays to check, and if they pass an .every test, push to the last one.然后你可以.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);
    }
}

This can then replace all of the functions, eg instead of doing然后这可以替换所有的功能,例如而不是做

uniqueNumber_3(2, 5)

you can do你可以做

uniqueNumber(2, 5, 3)

Write functions编写函数

random integer in inclusive range包含范围内的随机 integer

First of all, let's get that inclusive bounds random number calculation into its own function.首先,让我们把包含边界的随机数计算到它自己的 function 中。

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

set of unique numbers一组唯一的数字

And next, let's make use of Set to avoid all your "do I have one of these yet" checks to create your array of random numbers.接下来,让我们使用Set来避免所有“我是否有其中之一”检查来创建随机数数组。 Just keep adding random numbers into your set until it has the desired number of elements.只需不断将随机数添加到您的集合中,直到它具有所需数量的元素。 A Set can be spread back to an Array.一个集合可以传播回一个数组。 Beware , this version doesn't attempt to avoid endless loops or protect against invalid arguments such as what happens when N is zero.请注意,此版本不会尝试避免无限循环或防止无效 arguments,例如当 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];
}

an array of N things N 个事物的数组

And lastly you'll want a way to make an array of n things where the thing is defined by a function. There are numerous ways of accomplishing this , but Array.from is almost exactly what you need, you just need to pass it an object that defines a length property.最后,您需要一种方法来制作n 个事物的数组,其中事物由 function 定义。有多种方法可以实现这一点,但Array.from几乎正是您所需要的,您只需要将其传递给object 定义了length属性。

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

Use your functions使用你的功能

Armed with those 3 things, you can much more concisely write your code to generate an array of 4 such sets of unique numbers.有了这 3 个东西,您就可以更简洁地编写代码来生成一个包含 4 个这样的唯一数字集的数组。

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

Working example below:下面的工作示例:

 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM