【问题标题】:Javascript - Creating number with specific formula modulo11Javascript - 使用特定公式模11创建数字
【发布时间】:2017-02-15 13:30:28
【问题描述】:

我为捷克税号 (IČO) 创建了以下生成器。我知道肯定有更好的方法可以在 javascript 中编写代码。我是初学者,我想看看如何正确编写我的代码。这个数字是用特殊的公式创建的,它有 8 个数字,最后一个数字是基于 modulo11 的,你可以在下面的代码中看到。

感谢您的回复。

 //Generation of single random numbers as variables
 var a = Math.floor(Math.random() * 10);
 var b = Math.floor(Math.random() * 10);
 var c = Math.floor(Math.random() * 10);
 var d = Math.floor(Math.random() * 10);
 var e = Math.floor(Math.random() * 10);
 var f = Math.floor(Math.random() * 10);
 var g = Math.floor(Math.random() * 10);
 //Formula for tax number
 var formula = a * 8 + b * 7 + c * 6 + d * 5 + e * 4 + f * 3 + g * 2;
 var modulo11 = formula % 11;
 if (modulo11 === 0) {
   var h = 1;
 } else if (modulo11 === 1) {
   var h = 0;
 } else {
   var h = 11 - modulo11;
 };
 //Completing tax number
 var identificationNumber = "" + a + b + c + d + e + f + g + h;
 //displaying number in console
 console.log(identificationNumber);

【问题讨论】:

  • 除了一些风格的东西,代码有什么问题?你认为应该更好的是什么? (如果这行得通,我建议阅读codereview.stackexchange.com 上的How to AskWhat topics can I ask about here? 页面,并在适当的时候考虑在此处而不是此处发布。)
  • 它工作正常,但我认为我重复了很多代码,并且应该更有效地编写前 7 位数字(7 个随机数)的代码。
  • 我看不出你的代码有任何问题,如果它工作正常,老实说为什么要改变它......这并不总是关于“更少”的代码行......你还需要考虑到可读性方面。
  • 那么这不是 SO 的问题。正如我所说,它可能codereview.stackexchange.com的一个。
  • 我投票结束这个问题,因为它是一个代码审查问题。 可能codereview.stackexchange.com 的主题,但请先查看他们的帮助。

标签: javascript math modulo


【解决方案1】:
  • 利用Array数据结构存储a,b,...g

  • 然后通过(8- indexOfItem) * item“映射”这个数组

    ?? 所以,对于 index = 0 的 1ˢᵗ 项目,我们将有 (8 - 0) * a -➡ 8* a

    ?? 2ⁿᵈ 项目➡ (8 -1) * b7 *b

    ??....等等。

  • 然后使用“reduce”计算总和。

  • 然后用“join”代替""+ a +b + ....+ g+ h

function getH(modulo11) {
 if (modulo11 === 0)  return 1;
 if (modulo11 === 1)  return 0;
 return 11 - modulo11;
}

//Generation of single random numbers as variables
const numbers= Array.from({length: 7},(v, k) =>Math.floor(Math.random() * 10))  

 //Formula for tax number
const formula= numbers.map((n, i) => (8 - i) * n).reduce((total, next) => total+ next , 0)// alternative of sum : a * 8 + b * 7 + c * 6 + d * 5 + e * 4 + f * 3 + g * 2

const h= getH(formula % 11);

 //Completing tax number
const identificationNumber = [...numbers, h].join('');
 //displaying number in console
 console.log(identificationNumber);

【讨论】:

  • 没听说过mapFnArray.from的第二个参数
  • 我的意思是我还没有真正使用过Array.from 和它的API。感谢您提供回调示例。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-10-25
  • 2020-02-29
  • 2023-03-10
  • 1970-01-01
  • 2019-04-25
  • 2020-07-16
  • 1970-01-01
相关资源
最近更新 更多