2017-02-15 70 views
1

我爲捷克稅號(IČO)創建了以下生成器。我知道如何在JavaScript中編寫代碼當然有更好的方法。我是初學者,我想看看如何正確編寫我的代碼。這個數字是用特殊的公式創建的,它有8個數字,最後一位數字是基於模數11的,你可以在代碼中看到。Javascript - 創建具有特定公式的數字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);

+2

除了幾個風格的東西,什麼是錯的代碼?你認爲應該更好的是什麼? (如果這是工作,我會建議閱讀[如何問](http://codereview.stackexchange.com/help/how-to-ask)和[我可以問什麼問題?](http ://codereview.stackexchange.com/help/on-topic)http://codereview.stackexchange.com上的網頁,並考慮發佈,而不是在這裏,如果適當的話。) –

+0

它工作正常,但我認爲我重複很多的代碼,並且前7位數字(7個隨機數字)的代碼應該更有效地寫入。 – LadaWalker

+0

我認爲你的代碼沒有任何問題,如果它工作正常,爲什麼要改變它......它並不總是關於'少'的代碼行......你還需要考慮可讀性的方面。 –

回答

2
  • Array數據結構以效益來存儲ab,... g

  • 然後通過(8- indexOfItem) * item

    所以 「地圖」 該陣列中,對於具有索引= 01ˢᵗ項,我們將有(8 - 0) * a-➡8* a

    爲2ⁿᵈ項目➡(8 -1) * b7 *b

    ....等等。

  • 然後用「減少」來計算總和。

  • 然後使用 「加入」,而不是""+ 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);

+0

從未聽說過''mapFn',['Array.from']的第二個參數(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from) –

+0

don沒有明白你的意思。 @NinaScholz你能解釋更多 –

+0

我的意思是我沒有真正使用'Array.from'和它的API。感謝您使用回調的示例。 –

相關問題