# 努力让随机名称生成器正常工作

##### 问题描述投票：0回答：6

const randomName = {
prefix: ['Bramble', 'Lion', 'Owl'],
suffix: ['Paw', 'Throat', 'Tail']
};

let firstHalf = () => {
switch(Math.floor(Math.random() * 10)){
case 0:
console.log(randomName.prefix[0])
break;
case 1:
console.log(randomName.prefix[1])
break;
case 2:
console.log(randomName.prefix[2])
break;
};
};

let secondHalf = () => {
switch(Math.floor(Math.random() * 10)){
case 0:
console.log(randomName.suffix[0])
break;
case 1:
console.log(randomName.suffix[1])
break;
case 2:
console.log(randomName.suffix[2])
break;
};
};

console.log(`Your warrior name is \${firstHalf()} \${secondHalf()}!`);

javascript random generator
##### 6个回答
1

const randomName = {
prefix: ['Bramble', 'Lion', 'Owl'],
suffix: ['Paw', 'Throat', 'Tail']
};
function getRand(arr){
return arr[Math.floor(Math.random()*arr.length)]
}
console.log(`Your warrior name is \${getRand(randomName.prefix)} \${getRand(randomName.suffix)}!`);

0

Math.random()

0

1. firstHalf
secondHalf
return
任何东西。
2. 您的
Math.floor(Math.random() * 10)
会产生介于
0
9
之间的随机数，而您只有
3
选项。将
10
替换为 3`。或者...使用数组的长度。
3. 如果您使用的是开关的条件，则不需要
switch
语句：
switch(myNumber){
case 0:
doStuffWith[0];
break;
case 1:
doStuffWith[1];
break;
case 2:
doStuffWith[2];
break;
};

doStuffWith[myNumber]

firstHalf

let firstHalf = () => {
const name = randomName.prefix[Math.floor(Math.random() * randomName.prefix.length)];
console.log('firstHalf', name);
return name;
};

0

const randomName = {
prefix: ['Bramble', 'Lion', 'Owl'],
suffix: ['Paw', 'Throat', 'Tail']
};

firstHalf = randomName.prefix[randomNumberBetween(0, 3)];
secondHalf = randomName.suffix[randomNumberBetween(0, 3)];

const randomName = {
prefix: ['Bramble', 'Lion', 'Owl'],
suffix: ['Paw', 'Throat', 'Tail']
};

firstHalf = randomName.prefix[randomNumberBetween(0, randName.prefix.length)];
secondHalf = randomName.suffix[randomNumberBetween(0, randName.suffix.length)];

0

-1

function random(min, max) {
let delta = max - min;
return min+Math.round(Math.random()*delta);
}

let firstHalf = randomName.prefix[random(0, randomName.prefix.length-1)];