繁体   English   中英

如何根据传递给函数的参数更改变量名?

[英]How can I change a variable name based on a parameter passed to a function?

我有一个名为nameGenerator()的函数,该函数将变量category用作参数。

在定义此功能之前,我有两个“对”的单词列表数组: djentWords1djentWords2 ,然后是hardcoreWords1hardcoreWords2

nameGenerator()定义以下变量:

  1. firstNumsecondNum
  2. firstWordsecondWord
  3. bandName

该函数会生成两个随机数( firstNumsecondNum ),介于0和djentWords1djentWords2hardcoreWords1hardcoreWords2的长度之间。 我的问题是:我可以给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;
}

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

为什么不使用对象(关联数组)?

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

您需要将这些变量声明为数组属性。 尝试这个 :

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM