繁体   English   中英

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

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

我正在学习 JS,我想制作自己的小应用程序,其中我在 arrays 中存储了许多随机的唯一数字。我的代码工作正常,但我想制作许多 arrays 并且我遇到了大 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>

通过使第三个参数指示最多搜索多少个索引来概括 function。 然后你可以.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)

编写函数

包含范围内的随机 integer

首先,让我们把包含边界的随机数计算到它自己的 function 中。

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

一组唯一的数字

接下来,让我们使用Set来避免所有“我是否有其中之一”检查来创建随机数数组。 只需不断将随机数添加到您的集合中,直到它具有所需数量的元素。 一个集合可以传播回一个数组。 请注意,此版本不会尝试避免无限循环或防止无效 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];
}

N 个事物的数组

最后,您需要一种方法来制作n 个事物的数组,其中事物由 function 定义。有多种方法可以实现这一点,但Array.from几乎正是您所需要的,您只需要将其传递给object 定义了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);

暂无
暂无

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

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