2016-01-11 2 views
0

Я пытаюсь создать генератор случайных имен, который берет свое имя и фамилию из отдельных файлов. Какой самый простой способ сделать это, сохраняя файлы ресурсов легко изменяемыми?получить случайные объекты из отдельного файла

Благодарим за помощь!

Edit: функция

//---------------------first js-file humanVillages.js 
 

 
var nameSyllables = ["aber", "ac", "acc", "ock", "afon", "avon", "ar", "ard"]; 
 

 
function CreateNewHumanName() 
 
{ 
 
    //Creates a first name with 1-3 syllables 
 
    var firstName = ""; 
 
    var numberOfSyllablesInFirstName = Math.floor(getRandom(2, 5)); 
 
    for (var i = 0; i < numberOfSyllablesInFirstName; i++) 
 
    { 
 
     firstName += nameSyllables[Math.floor(getRandom(0, (nameSyllables.length + 1)))]; 
 
    } 
 
    
 
    var firstNameLetter = firstName[0]; 
 
    firstName = firstName.slice(1); 
 
    firstNameLetter = firstNameLetter.toUpperCase(); 
 
    firstName = firstNameLetter + firstName; 
 

 
    //Creates a second name with 2-4 syllables 
 
    var secondName = ""; 
 
    var numberOfSyllablesInSecondName = Math.floor(getRandom(4, 6)); 
 
    for (var i = 0; i < numberOfSyllablesInSecondName; i++) 
 
    { 
 
     secondName += nameSyllables[Math.floor(getRandom(0, (nameSyllables.length + 1)))]; 
 
    } 
 

 
    var secondNameLetter = secondName[0]; 
 
    secondName = secondName.slice(1); 
 
    secondNameLetter = secondNameLetter.toUpperCase(); 
 
    secondName = secondNameLetter + secondName; 
 

 
    // var completeName = firstName + " " + secondName; 
 
    var completeName = firstName; 
 
    return completeName; 
 
} 
 

 

 

 
//-------------second js file scripts.js 
 

 
// Declare the Object of Village, with name, 
 
// number of villagers and array of villager objects 
 
function Village(villageName, villagersAmount, villagersList, villageSizeDescriptor) { 
 
    this.villageName = villageName; 
 
    this.villagersAmount = villagersAmount; 
 
    this.villagersList = villagersList; 
 
    this.villageSizeDescriptor = villageSizeDescriptor; 
 
}; 
 

 
Village.prototype.villageName = function() { 
 
    return this.villageName; 
 
}; 
 
Village.prototype.villagersAmount = function() { 
 
    return this.villagersAmount; 
 
}; 
 
Village.prototype.villagersList = function() { 
 
    return this.villagersList; 
 
}; 
 
Village.prototype.villageSize = function() { 
 
    return this.villageSize; 
 
}; 
 
console.log("Village created correctly"); 
 

 

 
// Declare the Object of Villager, with preset first_name, 
 
function Villager(firstName) { 
 
    this.firstName = firstName; 
 
}; 
 
Villager.prototype.firstName = function() { 
 
    return this.firstName; 
 
}; 
 
console.log("Villager created correctly"); 
 

 
// Random Number Generator for incremental village size choices 
 
function getRandom(min, max) { 
 
    return Math.random() * (max - min) + min; 
 
}; 
 

 

 
$(document).ready(function() { 
 
    $("form#create_village").submit(function(event) { 
 
    event.preventDefault(); 
 
// Gather input for Village Creation 
 
    var villageSizeInput = parseInt($("#size").val()); 
 
    var villagersAmount = 0; 
 
    var villageSizeDescriptor = ""; 
 
// Use manual input for amount of villagers if selected and input is given 
 
// Otherwise take villageSizeInput to switch to right random number range 
 
    if (villageSizeInput == 0 && $("input#amount").val() == "") { 
 
     alert("Please enter a value if you choose manual input!") 
 
    } else if (villageSizeInput == 0) { 
 
     villagersAmount = parseInt($("input#amount").val()); 
 
    } else if (villageSizeInput == 1){ 
 
     villagersAmount = Math.floor(getRandom(0, 50000)); 
 
    } else { 
 
     switch (villageSizeInput) { 
 
     case 2: 
 
      villagersAmount = Math.floor(getRandom(0, 100));   
 
      break; 
 
     case 3: 
 
      villagersAmount = Math.floor(getRandom(100, 500));   
 
      break; 
 
     case 4: 
 
      villagersAmount = Math.floor(getRandom(500, 1000));   
 
      break; 
 
     case 5: 
 
      villagersAmount = Math.floor(getRandom(1000, 2000)); 
 
      break; 
 
     case 6: 
 
      villagersAmount = Math.floor(getRandom(1000, 5000)); 
 
      break; 
 
     case 7: 
 
      villagersAmount = Math.floor(getRandom(5000, 10000)); 
 
      break; 
 
     case 8: 
 
      villagersAmount = Math.floor(getRandom(10000, 25000)); 
 
      break; 
 
     case 9: 
 
      villagersAmount = Math.floor(getRandom(25000, 50000));   
 
      break; 
 
     } 
 
    } 
 
// Take villagersAmount to set corresponding verbal size descriptor 
 
    if (villagersAmount < 100) { 
 
     villageSizeDescriptor = "Thorp"; 
 
    } else if (villagersAmount < 500) { 
 
     villageSizeDescriptor = "Hamlet"; 
 
    }else if (villagersAmount < 1000) { 
 
     villageSizeDescriptor = "Village"; 
 
    }else if (villagersAmount < 2000) { 
 
     villageSizeDescriptor = "Small Town"; 
 
    }else if (villagersAmount < 5000) { 
 
     villageSizeDescriptor = "Large Town"; 
 
    }else if (villagersAmount < 10000) { 
 
     villageSizeDescriptor = "Small City"; 
 
    }else if (villagersAmount < 25000) { 
 
     villageSizeDescriptor = "Large City"; 
 
    }else { 
 
     villageSizeDescriptor = "Metropolis"; 
 
    } 
 
//create instance of Village and Villager 
 
    //call on function in humanVillages.js to randomly create a villageName 
 
    var newVillageName = CreateNewHumanName(); 
 
    var newVillage = new Village(newVillageName, villagersAmount, [], villageSizeDescriptor) 
 
    var newVillager = new Villager("Bob"); 
 
// Create output of Village 
 
    $("#villageType").text(newVillage.villageSizeDescriptor); 
 
    $("#villagersAmount").text(newVillage.villagersAmount); 
 
    $("#villageName").text(newVillage.newVillageName); 
 
// Random creation of Villagers 
 
    for (var index = 0; index < villagersAmount; index += 1) { 
 
     newVillage.villagersList.push(newVillager.firstName); 
 
     $("ul#villagers_names").append("<li><span class='villager'>" + newVillager.firstName + "</span></li>"); 
 
    } 
 
// Reset manual Input Value 
 
    $("input#amount").val(""); 
 
    }); 
 
});
<!DOCTYPE html> 
 
<html> 
 
\t <head> 
 
\t \t <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"> 
 
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css"> 
 
    <link rel="stylesheet" href="css/main.css" media="screen" title="no title" charset="utf-8"> 
 
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> 
 
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script> 
 
    <script src="js/scripts.js"></script> 
 
    <script src="resources/humanVillages.js"></script> 
 
    <title>Village Creator 1.0</title> 
 
\t </head> 
 
\t <body> 
 

 
\t \t <div id="input"> 
 
\t \t \t <!-- Selecting input for the village creation --> 
 
\t \t \t <h3>Create a village!</h3> 
 
\t \t \t <form id="create_village" onsubmit="return false;"> 
 
\t \t \t \t <table> 
 
\t \t \t \t \t <tbody> 
 
\t \t \t \t \t \t <tr> 
 
\t \t \t \t \t \t \t <td>Select a town size</td> 
 
      \t <td> 
 
      \t \t <select id="size"> 
 
      \t \t \t <!-- Selecting town size by increment --> 
 
\t \t \t \t \t \t \t \t \t <option value="0"selected="">Manual</option> 
 
\t \t \t \t \t \t \t \t \t <option value="1">Any</option> 
 
\t \t \t \t \t \t \t \t \t <option value="2">Thorp</option> 
 
\t \t \t \t \t \t \t \t \t <option value="3">Hamlet</option> 
 
\t \t \t \t \t \t \t \t \t <option value="4">Village</option> 
 
\t \t \t \t \t \t \t \t \t <option value="5">Small Town</option> 
 
\t \t \t \t \t \t \t \t \t <option value="6">Large Town</option> 
 
\t \t \t \t \t \t \t \t \t <option value="7">Small City</option> 
 
\t \t \t \t \t \t \t \t \t <option value="8">Large City</option> 
 
\t \t \t \t \t \t \t \t \t <option value="9">Metropolis</option> 
 
\t \t \t \t \t \t \t \t </select> 
 
\t \t \t \t \t \t \t </td> 
 
\t \t \t \t \t \t \t <td> 
 
\t \t \t \t \t \t \t \t <!-- Selecting town size by specific numeric input --> 
 
\t \t \t \t \t \t \t \t <label for="amount">The amount of villagers: </label> 
 
\t  \t \t \t \t <input type="number" name="amount" id="amount"> 
 
\t \t \t \t \t \t \t </td> 
 
\t \t \t \t \t \t </tr> 
 
\t \t \t \t \t \t <tr> 
 
\t \t \t \t \t \t \t <td>Select a town name</td> 
 
      \t <td> 
 
      \t \t <select id="name"> 
 
      \t \t \t <!-- Selecting town name by random racial name --> 
 
\t \t \t \t \t \t \t \t \t <option value="0"selected="">Manual</option> 
 
\t \t \t \t \t \t \t \t \t <option value="1">Random Drarven</option> 
 
\t \t \t \t \t \t \t \t \t <option value="2">Random Elven</option> 
 
\t \t \t \t \t \t \t \t \t <option value="3">Random Gnome</option> 
 
\t \t \t \t \t \t \t \t \t <option value="4">Random Orc</option> 
 
\t \t \t \t \t \t \t \t \t <option value="5">Random Halfling</option> 
 
\t \t \t \t \t \t \t \t \t <option value="6">Random Human</option> 
 
\t \t \t \t \t \t \t \t \t <option value="7">Random Other</option> 
 
\t \t \t \t \t \t \t \t </select> 
 
\t \t \t \t \t \t \t </td> 
 
\t \t \t \t \t \t \t <td> 
 
\t \t \t \t \t \t \t \t <!-- Selecting town name by specific spelled input --> 
 
\t \t \t \t \t \t \t \t <label for="name">The name of the village: </label> 
 
\t  \t \t \t \t <input type="text" name="name" id="name"> 
 
\t \t \t \t \t \t \t </td> 
 
\t \t \t \t \t \t </tr> 
 
    \t \t \t \t </tbody> 
 
    \t \t \t </table> 
 
\t  
 
\t  <button type="submit" class="btn btn-submit">Create!</button> 
 
\t  </form> 
 
\t \t </div> 
 

 
\t \t <div id="output"> 
 
\t \t \t <h3>Here there be a village!</h3> 
 
\t \t \t <!-- Output of village parameters --> 
 
\t \t \t <table> 
 
\t \t \t \t <tr> 
 
\t \t \t \t \t <th>Settlement Name</th> 
 
\t \t \t \t \t <td><span id="villageName"></span></td> 
 
\t \t \t \t </tr> 
 
\t \t \t \t <tr> 
 
\t \t \t \t \t <th>Settlement Type</th> 
 
\t \t \t \t \t <td><span id="villageType"></span></td> 
 
\t \t \t \t </tr><tr> 
 
\t \t \t \t \t <th>Population</th> 
 
\t \t \t \t \t <td><span id="villagersAmount"></span></td> 
 
\t \t \t \t </tr> 
 
\t \t \t \t <tr> 
 
\t \t \t \t \t <th>Villager Names</th> 
 
\t \t \t \t \t <td><ul id="villagers_names"></ul></td> 
 
\t \t \t \t </tr> 
 
\t \t \t </table> 
 
\t \t </div> 
 
\t \t 
 
\t </body> 
 
</html>

+0

Я, кажется, делает все правильно в вызове функции и генерации данных, я как-то я не в состоянии экспортировать данные в новую переменную – lolcat

+0

проверки этого учебника http://www.sitepoint.com/understanding- requirejs-for-effective-javascript-module-loading /. Это поможет вам понять requirejs. Это очень просто. – pro

ответ

1

Извлекает требуют() в узле, он позволяет получить доступ к объектам и функциям, которые, возможно, на отдельные файлы.

file1: nums.js

var obj = { 
    name: 'jack', 
    age: 30 
}; 

module.exports = obj; //exports the object 

file2: app.js

var nums = require('./nums'); 

console.log(nums); // prints --> { name: 'jack', age: 30 } 

ОБНОВЛЕНО:

file1: nums.js

var arr = [{ 
    name: 'jack', 
    age: 30 
    }, { 
    name: 'a', 
    age:40 
    }, { 
    name: 'abc', 
    age:40 
}]; 

module.exports = arr; 

file2: приложение. js

var nums = require('./nums'); 

var rand = Math.floor(Math.random() * nums.length); 

console.log(rand); 
console.log(nums[rand]); 
+0

Я боюсь, что документация для меня слишком сложна, чтобы следовать еще без посторонней помощи ... – lolcat

+0

Я отправил пример – pro

+0

Хотя ваш ответ верен, я предполагаю, что технология использует то, что OP создает веб-сайт, а не service.js, поэтому он может не использовать 'require()' – caulitomaz

Смежные вопросы