簡體   English   中英

Math.random() 放入函數時生成相同的數字

[英]Math.random() generating same number when put in a function

嗨,我正在做一個反應項目,我必須在其中生成隨機 ID,所以我做了這個功能

const idGenerator = () =>{
    Math.floor(Math.random() * 1000000)
}

當我像這樣直接使用它時,它工作正常會生成不同的 ID

{ 
   id:Math.floor(Math.random() * 1000000) 
}

但是當我創建函數並像這樣使用它時,它會生成相同的 id,這是為什么?

const idGenerator = () =>{
    Math.floor(Math.random() * 1000000)
}
// using it to make an object
{
   id: idGenerator 
}

您是否也嘗試過使用 return 語句?

const idGenerator = () =>{
    return Math.floor(Math.random() * 1000000)
}

或更短

const idGenerator = () => Math.floor(Math.random() * 1000000);

 const idGenerator = () => Math.floor(Math.random() * 1000000); let obj1 = { id1: idGenerator(), id2: idGenerator() } console.log(obj1);

您還需要使用括號()執行該函數,否則您的屬性將保存對該函數的引用

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM