简体   繁体   中英

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:

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.

Now my Questions:

N° 1: How can I create a lot of big Objects with the same attribute except 1?

N° 2: Why do I get the same Value twice? It doesn't really make sense to me. Am I missing something?

You have v1=template; and v2=template; , so v1 and v2 are the same object.

If you want to copy template, use

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

v1 and v2 are just references to the template object. Essentially, v1 and v2 are the same. Look at the console here. v1 is a random value and v2 is also random, but it is overridden by 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() :

 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) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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