'I need help doing a condition of a function and then a function out of that condition
I need help, I've writen an code that randomly assigns an alliance to the user, then I wanted to do a condition that runs a function if the user gets a certain alliance, this means, if you get marine in the next line it appears a role from the marines, or if you get revolucionary army it appears a role from the revolucionary army. Note: This roles would also be random as the alliance.
This is my code:
function capFirst(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min)) + min;
}
function alliance(){
var alliance = ["Revolucionary Army","Marine","Pirate","Bounty Hunter","Cipher Pol","Royalist","Celestial Dragon"];
var alliance = capFirst(alliance[getRandomInt(0, alliance.length + 1)]);
document.getElementById("alliance").innerHTML = alliance;
}
/* Rank */
if (true) {
var alliance = 'Revolucionary Army';
function rank(){
var rank = ["Leader","Chief of Staff","Army Commander","Officer","Member","Associate"];
var rank = capFirst(rank[getRandomInt(0, rank.length + 1)]);
document.getElementById("rank").innerHTML = rank;
}
} else {
var alliance = 'Marine';
function rankmarine(){
var rank = ["Fleet Admiral","Admiral","Vice Admiral","Rear Admiral"];
var rank = capFirst(rank[getRandomInt(0, rank.length + 1)]);
document.getElementById("rank").innerHTML = rank;
}
}
Solution 1:[1]
Make a function with the condition (if-else or switch) inside it. Like this
let alliance = "";
function capFirst(alli) {
return alli.charAt(0).toUpperCase() +alli.slice(1);
}
function generateAlliance(){
var alliances = ["Revolucionary Army","Marine","Pirate","Bounty Hunter","Cipher Pol","Royalist","Celestial Dragon"];
alliance = capFirst(alliances[getRandomInt(0, alliance.length + 1)]);
document.getElementById("alliance").innerHTML = alliance;
}
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min)) + min;
}
/* Rank */
function assignRank(){
var ranks = [];
if (alliance === "Revolucionary Army") {
ranks = ["Leader","Chief of Staff", "Army", "Commander", "Officer", "Member", "Associate"];
} else if(alliance === "Marine") {
ranks = ["Fleet Admiral","Admiral","Vice Admiral","Rear Admiral"];
}
var rank = capFirst(ranks[getRandomInt(0, ranks.length + 1)]);
document.getElementById("rank").innerHTML = rank;
}
link to fiddle: https://jsfiddle.net/wLoqejp5/
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
