Reputation: 143
Wasn't sure how to title what I'm looking for properly so I'll try and explain
I have a function
function cat(name, job, height){
console.log(name);
}
and I'm trying to randomise the 3 variables using the following code
let Array = ['jim, cook, 5','nick, dog, 2'];
const RandomMake = Math.floor(Math.random() * Array.length);
let Random = Array[RandomMake];
so say Random
output's jim, cook, 5
i'd like to use those variables within my function.
cat(Random);
Obviously I'm not making a cat generator but it explains what I need. I can't randomise each individual value it must be the group of items (name job height). I'm not sure if this is possible or if i'm just forgetting about a function that will allow me to do this. But it's definitely puzzled me... Thanks in advance for the help :) Always learning.
Upvotes: 0
Views: 44
Reputation: 370789
You can split the randomly selected string by ,
and spread the result into the call of cat
:
function cat(name, job, height){
console.log(name);
}
const arr = ['jim, cook, 5','nick, dog, 2'];
const randomIndex = Math.floor(Math.random() * arr.length);
const randomItem = arr[randomIndex];
cat(...randomItem.split(', '));
But, if possible, it would make a bit better organizational sense to have array of objects rather than an array of strings:
function cat({ name, job, height }){
console.log(name);
}
const arr = [{
name: 'jim',
job: 'cook',
height: 5
}, {
name: 'nick',
job: 'dog',
height: 2,
}];
const randomIndex = Math.floor(Math.random() * arr.length);
const randomItem = arr[randomIndex];
cat(randomItem);
Also, you should avoid declaring a variable named Array
- this will shadow the global window.Array
, which could easily cause problems. Best to give the variable a different name, like arr
.
Upvotes: 3