我正在嘗試創建一個函式來每次使用 Typescript 生成一個唯一的數字。由于某種原因,算術經常是不正確的。我已經擴展了下面的邏輯,并懷疑它與 Typescript/Javascript 的數字型別或 Math.ceil() 有關。如果有人可以教育我,我將不勝感激。
function nonce(){
const millidate = (new Date()).getTime();
const factor:number = 10000;
const codeTime:number = millidate*factor;
const codeEnd:number = Math.ceil(Math.random()*factor);
const codeMult:number = Math.ceil(Math.random()*10);
const codeBody:number = codeTime codeEnd;
const code:number = codeBody*codeMult;
console.log("Breakdown of " code ": ", codeTime, codeEnd, codeBody, codeMult);
return code;
};
nonce();
Playground 中一些測驗的影像

我使用 Typescript 的 Playground 來測驗這個,但它的性能在不同的環境中似乎是相同的。
uj5u.com熱心網友回復:
正如評論中所指出的,您的數字遠遠超過了系統限制。Number.MAX_SAFE_INTEGER在我的 64 位系統上:
9007199254740991 <- MSI
163469121917820770 <- your number
撥下來,或制作字串。
uj5u.com熱心網友回復:
要處理大數字(超過Number.MAX_SAFE_INTEGER),您需要使用BigInt()
沒有 BigInt:
9007199254740991 1 = 9007199254740992 // Right
9007199254740991 2 = 9007199254740992 // Wrong
9007199254740991 3 = 9007199254740994 // Right
使用 BigInt:
9007199254740991n 1n = 9007199254740992n //Right
9007199254740991n 2n = 9007199254740993n //Right
9007199254740991n 3n = 9007199254740994n //Right
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/331465.html
標籤:javascript 打字稿 数学
