简体   繁体   中英

Applying the same randomized array index value to two different variables

So basically this is what I'm trying to do. My code runs an AJAX get request on some external JSON data that's stored in arrays (as you can see below).

My code works great.

However I want to apply the same random value on the actual entry number that it's retrieving for both variable sa and ss.

var sa = (index.Of['10']['blah:blah'].label + ' ');
var ss = (index.Of['10']['blah:blah'].label);
var sS = (sa +  ss);

So I can do this with one variable with no issue, in the following code by doing it this way.

var sa = (index.Of[Math.floor(Math.random() * 10) + 1]['blah:blah'].label + ' ');
var ss = (index.Of[Math.floor(Math.random() * 10) + 1]['blah:blah'].label);
var sS = (sa +  ss);

BUT the issue is that I don't know of a way to apply the same math.floor randomization array value to both variables.

I'm stumped.

You can randomize a value once, save it to a variable and reuse:

var rand = Math.floor(Math.random() * 10) + 1;

var sa = (index.Of[rand]['blah:blah'].label + ' ');
var ss = (index.Of[rand]['blah:blah'].label);
var sS = (sa +  ss);
var r = Math.floor(Math.random() * 10) + 1;
var sa = (index.Of[r]['blah:blah'].label + ' ');
var ss = (index.Of[r]['blah:blah'].label);
var sS = (sa +  ss);

?

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