嗨,我正在做一个react项目,在这个项目中我必须生成随机id,所以我将这个函数设置为
const idGenerator = () =>{
Math.floor(Math.random() * 1000000)
}
当我像这样直接使用它时,它可以很好地生成不同的ids
{
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);
此外,您需要执行带有括号()
的函数,否则您的属性将保留对函数的引用