var name = ['C1', 'C2', 'C3'][Math.floor(Math.random() * 3)]
var bgimg = ['C1bg.jpeg', 'C2bg.jpeg', 'C3bg.jpeg'][Math.floor(Math.random() * 3)]
var profile_image_url = ['C1logo.png', 'C2logo.png', 'C3logo.png'][Math.floor(Math.random() * 3)]
var description = ['C1 desc', 'C2 desc', 'C3 desc'][Math.floor(Math.random() * 3)]
请注意不好的例子。你如何使变量随其他各自的变量随机变换,因此C1名称将带有C1标识& desc而不是每个部分都是随机的?
找到How to get n no elements randomly from an array和Getting a random value from a JavaScript array,但找不到如何将其作为一组变量?
答案 0 :(得分:1)
var bgimgs = ['C1bg.jpeg', 'C2bg.jpeg', 'C3bg.jpeg'];
var names = ['C1', 'C2', 'C3'];
var profile_image_urls = ['C1logo.png', 'C2logo.png', 'C3logo.png'];
var descriptions = ['C1 desc', 'C2 desc', 'C3 desc'];
var rand = Math.floor(Math.random()*bgimg.length);
var bgimg = bgimgs[random];
var name = bgimgs[random];
var profile_image_url = profile_image_urls[random];
var description = descriptions[random];
答案 1 :(得分:1)
你走了。
获取所需数量的数组并从提供的数组中返回新数组和随机数组项的函数。
const name = ['C1', 'C2', 'C3'];
const bgimg = ['C1bg.jpeg', 'C2bg.jpeg', 'C3bg.jpeg'];
const profile_image_url = ['C1logo.png', 'C2logo.png', 'C3logo.png'];
const description = ['C1 desc', 'C2 desc', 'C3 desc'];
const getRandomSet = (...set) => {
let randomSet = [];
[...set].forEach( set => {
const randomIndex = Math.floor(Math.random() * set.length);
randomSet.push(set[randomIndex]);
});
return randomSet;
}
const radnomSetFromArray = getRandomSet(name, bgimg, profile_image_url, description);
console.log(radnomSetFromArray);

答案 2 :(得分:0)
试试这个 -
var arrIndex = Math.floor(Math.random() * 3)
然后使用这个随机索引访问变量集,如 -
name[arrIndex],bgimg[arrIndex],profile_img_url[arrIndex],description[arrIndex]
答案 3 :(得分:0)
更好的方法是使用对象数组吗?
var objs = [
{name: 'Obj 1', img: 'Obj image 1'},
{name: 'Obj 2', img: 'Obj image 2'},
{name: 'Obj 3', img: 'Obj image 3'}
];
var sortObj = objs[Math.floor(Math.random()*objs.length)];