Need help on using random to get a random string from array - javascript

I already know how to pull random from an array but this won't work. Trying to make an HTML game.
I use Caret.
I'm pretty new to coding but know most of the basics.
function person() {
...
interests = ["food", "clothes", "tech"]; //interest definition because I keep getting "undefined"
var rand = Math.floor(Math.random() * 3); //random var
instrestscho = interests[rand]; //interest random string puller that's not working
...
}
}

I spy an extra:
}
I'm guessing this is the error because everything else should work.
Also, if the point of this function is to grab a random interest, you may want to return it, like so:
function person() {
interests = ["food", "clothes", "tech"]; //interests definition
var rand = Math.floor(Math.random() * interests.length); //random var
return interests[rand]; //return interest random string
}
console.log( person() );

Related

Push a var in an array

Im fairly new to programming. Mostly I can find the solution to my problems online but not this time. I've found serveral posts about pushing a variable into an array, however when I console.log the array to check if the variable is actually in the array, he doesn't return the name of the variable that I want. What I get back is: [Card, Card], and what I want to see is: [card_Fireball, card_Waterbolt, etc]. The code I use is:
var Deck = [];
function Card(name, type, cost, points, damage, heal){
this.name = name;
this.type = type;
this.cost = cost;
this.points = points;
this.damage = damage;
this.heal = heal;
}
var card_Fireball = new Card("Fireball", "spell", 2, 1, 3, 0);
var card_Waterbolt = new Card("Waterbolt", "spell", 2, 1, 3, 0);
Deck.push(card_Fireball);
Deck.push(card_Waterbolt);
console.log(Deck);
The solution is probably fairly simple but I can't figure it out with my beginner experience :P Thanks for the help!!
You are doing everything correct just replace console.log with following:
console.log(JSON.stringify(Deck));
Access the card names with "Deck[x].name", where x is the index of the card in the array Deck.
To get all the names:
for(i=0;i<Deck.length;i++){
console.log(Deck[i].name);
}
Assuming you name all your cards the same way as you did in your example, you could use this to get the variable names:
for(i=0;i<Deck.length;i++){
console.log('card_' + Deck[i].name);
}
If you want to get an array of the variable names you have used, those are lost on the way.
In case you want an array of the names or any other property, try making a new array and pushing every value to it.
var names = [];
Deck.map(function(v) { names.push(v.name) })
console.log(names);
Output:
["Fireball", "Waterbolt"]

combining text into a variable name in javascript

i have looked for an answer to this, but im also not sure im using the correct wording to give me a good search result. So without further adoo.
I am trying to make a random name generator in JavaScript, and I don't want a 300 line switch if it can be avoided. No Jquery if it can be avoided, mainly as i want to learn how to code in JS, for no other reason than that. But if i have to use Jquery, so be it. Learning and all.
The idea is that the script will take the race, gender, then randomly select the first name, surname and proffesion from an array. I can get this to work in IF statements and switches. But I want to try it on as little code as possible. The example below is for humans, but the idea is to pretty much use any fantasy race... dwarves, elves... yes its for dungeons and dragons. Maybe later on use JSON for the array data, but that's later.
var HumanFemale = ["Diane","Laura","Amy"];
var HumanMale = ["Steve","Dave","Tony"];
var HumanS = ["Druss","Hale","Taylor"];
var Proff = ["Theif","Mercenary","Soldier"];
function chargen(race,gender){
var x = race.concat(gender);
var xs= race.concat('S');
document.getElementById("OutputR").innerHTML= race;
document.getElementById("OutputG").innerHTML= gender;
document.getElementById("OutputF").innerHTML= x[Math.floor(Math.random()*x.length)];
document.getElementById("OutputS").innerHTML=xs[Math.floor(Math.random()*xs.length)];
document.getElementById("OutputJ").innerHTML=Proff[Math.floor(Math.random()*Proff.length)];
}
Maybe I need dynamic variables, but i'm not sure how to convert text into a var name.
Thanks
I think an object probably makes your life a little easier, but the idea is generally the same as what you appear to have.
In JavaScript you can reference a property of an object like an array. This means that if you have a property name that can be variable, you can use the array convention to fetch the property instead of the "." convention.
Here's an example:
var example = {
"first": "hello",
"second": "world"
}
//Using dot-notation
alert(example.first); //alerts "hello"
alert(example.second) //alerts "world"
//Using array-notation
alert(example["first"]); //alerts "hello"
alert(example["second"]); //alerts "world"
Now, if the property we want is variable, we can't use the dot-notation, but we can use the array-notation:
var prop_name = "second";
//Using dot-notation
alert(example.prop_name); //throws an error (undefined property)
//Using array-notation
alert(example[prop_name]); //alerts "world"
So, if you create essentially a dictionary object, you may find it's easier/more concise to complete your task:
var dict = {
"Human": {
"Male": ["Steve", "Dave", "Tony"],
"Female": ["Diane", "Laura", "Amy"],
"Surname": ["Druss", "Hale", "Taylor"]
},
"Elf": {
"Male": [/* names */],
"Female": [/* names */],
"Surname": [/*names */]
}
}
function rand_attributes(race, gender) {
var first_name_index = Math.floor(Math.random() * dict[race][gender].length),
last_name_index = Math.floor(Math.random() * dict[race]["Surname"].length),
first_name = dict[race][gender][first_name_index],
last_name = dict[race]["Surname"][last_name_index];
//Now first_name and last_name each contain random values
//Do what you need to with those values from here
}
That code is untested, but it should at least conceptually work out.
Here's what I crudely chucked together.
var Proff=["Theif","Mercenary","Soldier"];
var CharacterName={};
CharacterName['human']={};
CharacterName['human']['female'] = new Array('Diane','Laura','Amy');
CharacterName['human']['male'] = new Array('Steve','Dave','Tony');
CharacterName['human']['surname'] = new Array('Druss','Hale','Taylor');
//just add more stuff here!
document.getElementById('OutputR').innerHTML= 'boo';
function chargen(race,gender){
document.getElementById('OutputR').innerHTML= race;
document.getElementById('OutputG').innerHTML= gender;
document.getElementById('OutputF').innerHTML= grabrandom(CharacterName[race][gender]);
document.getElementById('OutputS').innerHTML= grabrandom(CharacterName[race]['surname']);
document.getElementById('OutputJ').innerHTML= grabrandom(Proff);
}
function grabrandom(arrayofvalues){
return arrayofvalues[Math.floor(Math.random()*arrayofvalues.length)];
}
chargen('human','female');
It's nothing special and a couple of bits could be sharpened, but it's functional and gives you the idea on how it could be done.
The solution i got, heavily based on xjstratedgebx's responce.
var names = {
"Human": {
"Female": ["Diane","Laura","Amy"],
"Male": ["Steve","Dave","Tony"],
"Surname": ["Hall","Young","Taylor"]
}
}
function namegen(race,gender){
var firstname = names[race][gender][Math.floor(Math.random() * names[race][gender].length)];
var lastname = names[race]["Surname"][Math.floor(Math.random() * names[race]["Surname"].length)];
document.getElementById("OutputR").innerHTML= "Human";
document.getElementById("OutputG").innerHTML= "Female";
document.getElementById("OutputF").innerHTML= firstname;
document.getElementById("OutputS").innerHTML= lastname;
}

random quote without back to back

I'm trying to pull a random quote from an array. I need to display an initial quote and then get a new one, no same two quotes back to back. Here's what I got.
$(document).ready(function() {
var quoter = [{
quote: "I drink to make other people more interesting.",
author: "Ernest Hemingway"
}, {
quote: "Alcohol may be man's worst enemy, but the bible says love your enemy.",
author: "Frank Sinatra"
}, {
quote: "Reality is an illusion created by a lack of alcohol.",
author: "N.F. Simpson"
},{
quote: "Time is never wasted when you’re wasted all the time.",
author: "Catherine Zandonella"
},{
quote: "I feel bad for people who don’t drink. When they wake up in the morning, that’s as good as they’re going to feel all day.",
author: "Frank Sinatra"
}];
var randomQuote = Math.floor(Math.random() * quoter.length);
//$(function () {
//Set Original Quote
$('#quoteText').text(quoter[randomQuote].quote);
$('#authorText').text(quoter[randomQuote].author);
//});
$('#btnNew').click(function(evt) {
//prevent browser's default action
evt.preventDefault();
//getting a new random number to attach to a quote and setting a limit
var sourceLength = quoter.length;
var randomNumber = Math.floor(Math.random() * sourceLength);
//set a new quote
//while ( randomNumber <= sourceLength ) {
while (randomNumber === randomNumber){
var newQuoteText = quoter[randomNumber].quote;
var newQuoteGenius = quoter[randomNumber].author;
var timeAnimation = 500;
var quoteContainer = $('#quoteContainer');
//fade out animation with callback
quoteContainer.fadeOut(timeAnimation, function() {
//set text values
$('#quoteText').text(newQuoteText);
$('#authorText').text(newQuoteGenius);
//console.log(quoteText,authorText);
//fadein animation.
quoteContainer.fadeIn(timeAnimation);
});
break;
}; //end while loop
}); //end btnNew function
}); //end document ready
I need to do this by using a while loop. I can't figure out how to store the random quote (array value) and then compare it to the new random one to get a different random on if it's the same.
The HTML is here:
<div id="quoteContainer">
<p><span id="quoteText"></span><Br/></p>
—<span id="authorText"> </span>
</div>
You can have a simple variable store the previous value, then check to see if the random number is the same as the last time.
$(document).ready(function(){
//....your current above code
var lastQuote = randomQuote;
$(button).click(function(){
var thisQuote = Math.floor(Math.random() * sourceLength);
//This will only be entered if the two are equal
//The while loop ensures that if you get a new random number
//it won't be the same
while(thisQuote == lastQuote){
thisQuote = Math.floor(Math.random() * sourceLength);
}
//If you make it here a unique number has been found
lastQuote = thisQuote;
});
});
Your approach might result in an infinite loop. Won't happen, because the random-number generator is not perfect but it can be done easier:
Either shuffel the array and go down linearly (or construct a fancy generator if you want) or just delete every quote that has been shown already.

How do I print or call 1 return value from a function who takes multiple parameters?

I am trying to make a small video game where a player fights a monster. In it, I created a object "player", who uses a method called stats to return the players HP and Balance numbers. Dwarf will be my new object for now, as I will add other types later, and i'm trying to get document to write down the players stats, except in this case, individually. For now i'm using the player panel as a view to see how javascript will print the code, but later, I want to use specific div boxs to put in the players HP and Balance in 2 seperate fields. The problem i'm coming across is I can get the javascript code to print both variables together, but I cannot seem to call 1 or the other individually. Is there a way to do this? Also just for reference, when it prints the first line, it adds a coma, EX: 100, 250. Is there a way to remove that? Although I don't think it will be a issue if I get my first problem solved.
So how can I tell javascript that I only want to pull HP and write that.. or only pull Balance and write that? I tried to use indexing but that did not work.
var player = {
stats: function (hp, balance){
this.hp = hp;
this.balance = balance;
return [hp, balance]
}
}
var dwarf = Object.create(player);
document.getElementById("playerpanel").innerHTML += dwarf.stats(100, 250)
document.getElementById("playerpanel").innerHTML += dwarf.stats[1]
You can return an object, e.g.:
return {hp: hp, balance: balance};
Then pull just that property of the returned object:
//this executes the function and stores the returned object
var theCall = dwarf.stats(100, 250);
//this pulls the assigned property by name "balance"
document.getElementById("playerpanel").innerHTML += theCall.balance;
stats should probably not be a function, rather a nested object.
var Player = {
stats: {
hp: 0,
balance: 0
}
}
...
dwarf.stats.hp = 100;
console.log(dwarf.stats.hp); // 100
console.log(dward.stats); // { hp: 100, balance: 0 }
You can just return a object containing both variables. You can then refer to the individual fields using their field names hp and balance, see below:
var player = {
stats: function(hp, balance) {
this.hp = hp;
this.balance = balance;
return {
hp, balance
}
}
}
var dwarf = Object.create(player);
document.getElementById("playerpanel").innerHTML += dwarf.stats(100, 250).hp
document.getElementById("playerpanel").innerHTML += ','+dwarf.stats(100, 250).balance
<div id="playerpanel"></div>

JavaScript database correlation

I've been trying to 'correlate' between user picked answers and an object property name so that if the two matches then it will display what is inside.
My program is a recipe finder that gives back a recipe that consists of the ingredients the user picked.
my code currently looks like:
//property are the ingredients and the value are the recipes that contain those ingredients. The map is automatically generated
``var map = {
"pork" : [recipe1, recipe2, ...],
"beef" : [],
"chicken" :[],
}
//this gets the user pick from the dom
var cucumber = specificVegetable[7];
var lemon = specificFruits[0];
//Then this code finds the intersection of the recipe(recipes that use more than one ingredients)
function intersect(array1, array2)
{
return array1.filter(function(n) {
return array2.indexOf(n) != -1
});
}
var recipiesWithLemon = map["lemon"]; **// makes the lemon object is map**
var recipiesWithCucumber = map["cucumber"]; **// makes the cucumber object in map**
//Here is where I am stuck
function check(){
var both = intersect(recipiesWithLemon, recipiesWithCucumber);
if ( cucumber.checked && lemon.checked){
for (var stuff in map){
if(stuff="cucumber" && stuff="lemon"){
return both;
}
}
}
}
check();
so basically what I tried to do was I made my intersect and then if user pick is lemon and cucumber then look at the properties in the map object. if the name of the property equals to the exact string then return both. That was the plan but the code does not work and I'm not sure how to fix it.
My plan is to write code for every possible outcome the user may makes so I need to find the correlation between the user pick and the map which stores the recipe. I realize this is not the most effective way but I'm stumped on how to do it another way.
Thanks for the help.
Im using the open source project jinqJs to simplify the process.
I also changed your map to an array of JSON objects. If you must have the map object not as an array, let me know. I will change the sample code.
var map = [
{"pork" : ['recipe1', 'recipe2']},
{"beef" : ['recipe3', 'recipe4']},
{"peach" :['recipe5', 'recipe6']},
{"carrot" :['recipe7', 'recipe8']}
];
var selectedFruit = 'peach';
var selectedVeggie = 'carrot';
var selections = [selectedFruit, selectedVeggie];
var result = jinqJs().from(map).where(function(row){
for(var f in row) {
if (selections.indexOf(f) > -1)
return true;
}
return false;
}).select();
document.body.innerHTML += '<pre>' + JSON.stringify(result, null, 2) + '</pre><br><br>';
<script src="https://rawgit.com/fordth/jinqJs/master/jinqjs.js"></script>

Categories

Resources