我有一个名为nameGenerator()
的函数,它将变量category
作为参数。
在定义此函数之前,我有两对“wordlist”数组:djentWords1
和djentWords2
,然后是hardcoreWords1
和hardcoreWords2
。
nameGenerator()
定义以下变量:
firstNum
和secondNum
firstWord
和secondWord
bandName
该函数生成两个随机数(firstNum
和secondNum
),介于0和djentWords1
&的长度之间。 djentWords2
或hardcoreWords1
& hardcoreWords2
。我的问题是:我可以传递nameGenerator()
像“djent”或“hardcore”这样的参数,并根据该参数,让它使用适当的数组长度来生成随机数吗?这是按原样的功能:
//First category: djent
var djentWords1 = ["Aman", "Soul", "Cloud", "Calculate", "Pythagoran"];
var djentWords2 = ["NaaKi", "Circlet", "Cykul", "Consciousness", "Daaka"];
//Second category: hardcore
var hardcoreWords1 = ["SMASH", "RAGE", "LIFE", "THESE", "FIRST", "BRASS", "LAST"];
var hardcoreWords2 = ["FIST", "FIGHTER", "BREAKER", "SMASHER", "RUINER", "DAYS", "CHANCE"];
function nameGenerator (category){
//Randomize
var firstNum = Math.floor(Math.random() * categoryWords1.length); //categoryWords1 would either be djentWords1 or hardcoreWords1, based on the parameter passed to the function
var secondNum = Math.floor(Math.random() * categoryWords2.length); //categoryWords2 would either be djentWords2 or hardcoreWords2, based on the parameter passed to the function
var firstWord = categoryWords1[firstNum]; //firstWord = the word whose position corresponds to the first randomly-generated number
var secondWord = categoryWords2[secondNum]; //secondWord = the word whose position corresponds to the second randomly-generated number
var bandName = firstWord + secondWord;
}
提前致谢 - 希望这不会太令人困惑。非常感谢所有帮助。
答案 0 :(得分:3)
为什么不使用对象(关联数组)?
var words = {
djent: [
["Aman","Soul","..."],
["NaaKi","Circlet","..."]
],
hardcore: [
["..."],
["..."]
]
};
function nameGenerator(category) {
var bandName = words[category][0][Math.floor(Math.random()*words[category][0].length)]
+ words[category][1][Math.floor(Math.random()*words[category][1].length)];
return bandName;
}
答案 1 :(得分:0)
您需要将这些变量声明为数组属性。试试这个:
var djent = {
words1 : ["Aman", "Soul", "Cloud", "Calculate", "Pythagoran"],
words2 : ["NaaKi", "Circlet", "Cykul", "Consciousness", "Daaka"]
}
var hardcore = {
words1 : ["SMASH", "RAGE", "LIFE", "THESE", "FIRST", "BRASS", "LAST"],
words2 : ["FIST", "FIGHTER", "BREAKER", "SMASHER", "RUINER", "DAYS", "CHANCE"]
}
function nameGenerator (category){
var firstNum = Math.floor(Math.random() * window[category].words1.length)
, secondNum = Math.floor(Math.random() * window[category].words2.length)
, firstWord = window[category].words1[firstNum]
, secondWord = window[category].words2[secondNum]
, bandName = firstWord + secondWord;
return bandName;
}