0
I am trying to generate a name. Why won't this code work?
var names = ["Olivia", "Oliver", "Amelia", "Harry", "Isla", "Jack", "Emily", "George", "Ava", "Noah", "Lily", "Charlie", "Mia", "Jacob", "Sophia", "Alfie", "Isabella", "Fred", "Grace"]; var surnames = ["Smith", "Johnson", "Williams", "Jones", "Brown", "Davis", "Miller", "Wilson", "Moore", "Anderson", "Thomas", "Jackson", "White", "Harris", "Martin", "Thompson", "Garcia", "Martinez", "Taylor", "Robinson"]; function createName(toVariable) { var name = names[Math.floor(Math.random() * names.length)]; var surname = surnames[Math.floor(Math.random() * surnames.length)]; toVariable = name + " " + surname; } var botName = ""; createName(botName); console.log(botName);
2 Respostas
0
Because when you insert the botName variable as an argument into the createName function. You are actually passing it's value, not the variable itself.
Things like this are made by returning the output of the function.
var names = ["Olivia", "Oliver", "Amelia", "Harry", "Isla", "Jack", "Emily", "George", "Ava", "Noah", "Lily", "Charlie", "Mia", "Jacob", "Sophia", "Alfie", "Isabella", "Fred", "Grace"];
var surnames = ["Smith", "Johnson", "Williams", "Jones", "Brown", "Davis", "Miller", "Wilson", "Moore", "Anderson", "Thomas", "Jackson", "White", "Harris", "Martin", "Thompson", "Garcia", "Martinez", "Taylor", "Robinson"];
function createName() {
var name = names[Math.floor(Math.random() * names.length)];
var surname = surnames[Math.floor(Math.random() * surnames.length)];
return name + " " + surname;
}
botName = createName()
console.log(botName);
0
var names = ["Olivia", "Oliver", "Amelia", "Harry", "Isla", "Jack", "Emily", "George", "Ava", "Noah", "Lily", "Charlie", "Mia", "Jacob", "Sophia", "Alfie", "Isabella", "Fred", "Grace"];
var surnames = ["Smith", "Johnson", "Williams", "Jones", "Brown", "Davis", "Miller", "Wilson", "Moore", "Anderson", "Thomas", "Jackson", "White", "Harris", "Martin", "Thompson", "Garcia", "Martinez", "Taylor", "Robinson"];
function createName() {
var name = names[Math.floor(Math.random() * names.length)];
var surname = surnames[Math.floor(Math.random() * surnames.length)];
return name + " " + surname;
}
var botName = createName();
console.log(botName);
You don't need to send argument to function. Sending string variable to this function is just copying variable by value. But if you take an object (reference type) it will work:
function createName(person) {
var name = names[Math.floor(Math.random() * names.length)];
var surname = surnames[Math.floor(Math.random() * surnames.length)];
person.name = name + " " + surname;
}
var botName = {};
createName(botName);
console.log(botName.name);