0

我有一个函数nameGenerator(),它接受一个变量 ,category作为参数。

在定义这个函数之前,我有两个单词列表数组“对”:djentWords1and djentWords2,然后是hardcoreWords1and hardcoreWords2

nameGenerator()定义以下变量:

  1. firstNumsecondNum
  2. firstWordsecondWord
  3. bandName

该函数在 0 和&或&的长度之间生成两个随机数 ( firstNumand ) 。我的问题是:我可以传递像“djent”或“hardcore”这样的参数,并基于该参数,它是否使用适当的数组长度来生成随机数?这是功能原样:secondNumdjentWords1djentWords2hardcoreWords1hardcoreWords2nameGenerator()

//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;
}

在此先感谢 - 希望这不会太令人困惑。非常感谢所有帮助。

4

2 回答 2

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;
}
于 2013-02-19T03:01:16.917 回答
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;
}
于 2013-02-19T03:10:50.367 回答