简体   繁体   English

为什么我的随机函数两次返回相同的值

[英]Why does my random function return the same value twice

Context: I was creating a dummy website with some dummy Graphs. 上下文:我正在创建一个带有一些虚拟图的虚拟网站。 I needed some random value in similar js objects like this: 我需要像这样的类似js对象中的一些随机值:

object = {
  x: static,
  y: static,
  ...

  data: random
}

So I came up with something like this: 所以我想出了这样的东西:

 async function getOption() { return getRandom(); } async function setup() { let template = { static1: "xx", static2: "xx", option: 1 } let v1 = template; v1.option = await getOption(); let v2 = template; v2.option = await getOption(); console.log(await getOption(), await getOption()) console.log(v1.option, v2.option) } function getRandom() { return Math.floor(Math.random() * 100); } setup() 

But I've noticed something strange that I don't understand. 但是我注意到一些我不理解的奇怪现象。 I get the same "random" value twice every time if I want to assign a new number. 如果我想分配一个新的数字,我每次都会得到两次相同的“随机”值。 Furthermore, if I call it inside a console.log() , it works as expected. 此外,如果我在console.log()调用它,它会按预期工作。

Now my Questions: 现在我的问题:

N° 1: How can I create a lot of big Objects with the same attribute except 1? N°1:如何创建除1以外具有相同属性的许多大对象?

N° 2: Why do I get the same Value twice? N°2:为什么我两次获得相同的值? It doesn't really make sense to me. 这对我来说真的没有意义。 Am I missing something? 我想念什么吗?

You have v1=template; 您有v1=template; and v2=template; v2=template; , so v1 and v2 are the same object. ,因此v1和v2是同一对象。

If you want to copy template, use 如果要复制模板,请使用

v1 = {...template};
v2 = {...template};

v1 and v2 are just references to the template object. v1和v2只是对模板对象的引用。 Essentially, v1 and v2 are the same. 本质上,v1和v2是相同的。 Look at the console here. 在这里查看控制台。 v1 is a random value and v2 is also random, but it is overridden by v2: v1是一个随机值,v2也是随机值,但被v2覆盖:

 async function getOption() { return getRandom(); } async function setup() { let template = { static1: "xx", static2: "xx", option: 1 } let v1 = template; v1.option = await getOption(); console.log('v1:', v1.option) console.log('template:', template.option) let v2 = template; v2.option = await getOption(); console.log('v2:', v2.option) console.log('template:', template.option) console.log(v1.option, v2.option) } function getRandom() { return Math.floor(Math.random() * 100); } setup() 

EDIT: If you wanted to make copies, you could use assign() : 编辑:如果您想制作副本,则可以使用assign()

 let template = { static1: "xx", static2: "xx", option: 1 } var obj = Object.assign({}, template); template.option = "100" obj.option = "200" console.log(template.option, obj.option) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM