I'm trying to use the "database" I have made to cycle through some the quotes at random when the button is clicked and changing the existing quote in the HTML to the random quote and the existing author in the same way
var myDatabase = [
{quote:"I have learned silence from the talkative...", author:"Khalil Gibran"},
{quote: "One of the blessings of old friends that you can afford to be stupid with them." author:"Ralph Waldo Emmerson"},
{quote: "Once we accept our limits, we go beyond them." author:"Albert Einstein"}
];
var newQuote = document.getElementById('displayedQuote');
var newAuthor = document.getElementById('author');
$("#quoteButton").click(function() {
var rand = Math.floor(Math.random()*database.length)
newQuote = myDatabase.[rand].quote;
newAuthor = myDatabase.[rand].author;
});
Firstly your "Database" has syntax errors. It should read:
var myDatabase = [{
"quote": "I have learned silence from the talkative...",
"author": "Khalil Gibran"
}, {
"quote": "One of the blessings of old friends that you can afford to be stupid with them.",
"author": "Ralph Waldo Emmerson"
}, {
"quote": "Once we accept our limits, we go beyond them.",
"author": "Albert Einstein"
}];
Secondly, you're mixing vanilla JS with Jquery. Whilst this isn't technically wrong it's much easier to read if you just stick to one or the other
var newQuote = $('#displayedQuote');
var newAuthor = $('#newAuthor');
Lastly, the syntax in your click method is incorrect. You're assigning a value to the newQuote and newAuthor variables rather than manipulating the element. What you want to do is use the .text() method to add the object values to the DOM.
Also, you don't need the dot notation before the [rand] integer and you want myDatabase.length not database.length
$("#quoteButton").click(function() {
var rand = Math.floor(Math.random() * myDatabase.length)
newQuote.text(myDatabase[rand].quote)
newAuthor.text(myDatabase[rand].author)
});
Here's a working example: https://codepen.io/mark_c/pen/pExxQA
Something like that ?
var myDatabase = [
{quote:"I have learned silence from the talkative...", author:"Khalil Gibran"},
{quote: "One of the blessings of old friends that you can afford to be stupid with them." author:"Ralph Waldo Emmerson"},
{quote: "Once we accept our limits, we go beyond them." author:"Albert Einstein"}
];
var newQuote = document.getElementById('displayedQuote');
var newAuthor = document.getElementById('author');
$("#quoteButton").click(function() {
var rand = Math.floor(Math.random()*database.length)
$(newQuote).text(myDatabase[rand].quote);
$(newAuthor).text(myDatabase[rand].author);
});
Related
I am currently working on a project that already has provided me with this code on a separate js file:
function getRandomNumber(min, max) {
if (_TESTING) {
_mockRandomNumberCalls.push({min: min, max: max});
}
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1) + min);
}
Now, I am supposed to create a function that will call on a random answer from these multiple arrays on the js file I am using:
let positiveAnswers = [
"As I see it, yes",
"It is certain",
"It is decidedly so",
"Yes",
"Yes, definitely"
];
let negativeAnswers = [
"My reply is no",
"My sources say no",
"There is no way",
"No",
"Absolutely not!"
];
let maybeAnswers = [
"Ask again later",
"Better to not tell you now",
"Cannot predict now",
"Concentrate and ask again",
"Reply hazy try again"
];
const NO_QUESTION_WARNING = "You need to ask a question!";
So I know I need to use an if else statement for my function in order to get a random answer. In my project though, it says to call on the random answer by just adding 'getRandomNumber' so here is my code:
function chooseRandomAnswer(answerType) { `
let answertype = positiveAnswers, negativeAnswers, maybeAnswers;
if (answerType = positiveAnswers){
getRandomNumber();
} else {
if (answertype = negativeAnswers){
getRandomNumber();
}
}
I want to generate a random answer from the arrays that are provided for me, but I keep getting lost and javascript keeps telling me this will not work. I keep trying to find the answer but somewhere along the way I think I messed up my function. I know, I know, it's so evident that I am a beginner and maybe it is easier than I think.
Ok, let's walk through how to solve this problem from a complete beginners' perspective.
With this function,
function chooseRandomAnswer(answerType) {
// some code here
}
you need to be sure of these two things:
what information exactly is being given to the function?
what information exactly is being passed out of the function?
Which then begs the question, how do we become sure of these things? Your first step should be to log answerType to the console, like this:
function chooseRandomAnswer(answerType) {
console.log(answerType);
console.log(typeof answerType);
}
After this, run your code and check to see what the console says. I don't know exactly what it will show (and I don't think you currently do either), but my guess is that it could show a string of some kind, maybe "positive", "negative", or "maybe". The second console log will help you understand what the "type" is - is it a string, number, boolean, object, or something else?
Once you know, you'll be able to write something like this:
function chooseRandomAnswer(answerType) {
if (answerType === "positive" /* a guess on my part */) {
return positiveAnswers[getRandomNumber(0, ...)];
}
}
I've left the ... in the line so you can explore how to do this on your own. Look up how arrays work for help if you get stuck, this link is good:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array
Hope this helps!
I don't exactly know what you are trining to do, but here is a way to generate an random answer
const positiveAnswers = [ "As I see it, yes", "It is certain", "It is decidedly so", "Yes", "Yes, definitely" ];
const negativeAnswers = [ "My reply is no", "My sources say no", "There is no way", "No", "Absolutely not!" ];
const maybeAnswers = [ "Ask again later", "Better to not tell you now", "Cannot predict now", "Concentrate and ask again", "Reply hazy try again" ];
const NO_QUESTION_WARNING = "You need to ask a question!" ;
function chooseRandomAnswer(answerType)
{
var answer = '', nr=0;
switch (answerType)
{
case 'positiveAnswer':
case 1:
nr = Math.floor( Math.random() * positiveAnswers.length )
answer = positiveAnswers[nr]
break;
case 'negativeAnswer':
case -1:
nr = Math.floor( Math.random() * negativeAnswers.length )
answer = negativeAnswers[nr]
break;
case 'maybeAnswer':
case 0:
nr = Math.floor( Math.random() * maybeAnswers.length )
answer = maybeAnswers[nr]
break;
default:
answer = NO_QUESTION_WARNING
}
return answer;
}
How can i remove all instances of :smile: style emjois from a string using javascript? Here is an example below I got in JSON with :point_right: in it. I'd love to remove all of them from a string.
[ { service_name: 'Instagram',
title: 'Instagram: “:point_right: Real people, making real products from real plants, using their actual hands to put them in boxes that show up on your doorstep.…”',
text: '36 Likes, 2 Comments - “:point_right: Real people, making real products',
ts: '1523497358.000299' }
Just use String.prototype.replace() with a regular expression:
const input = 'Instagram: “:point_right: Real people, making real products from real plants, using their actual hands to put them in boxes that show up on your doorstep.…”';
const output = input.replace(/:\w+:/g, '');
console.log(output);
Assuming the emojis are all one word, between :s:
const obj = {
service_name: 'Instagram',
title: 'Instagram: “:point_right: Real people, making real products from real plants, using their actual hands to put them in boxes that show up on your doorstep.…”',
text: '36 Likes, 2 Comments - “:point_right: Real people, making real products',
ts: '1523497358.000299'
}
obj.title = obj.title.replace(/:[^ ]+:/g, '');
obj.text = obj.text.replace(/:[^ ]+:/g, '');
console.log(obj);
From this answer Replacing values in JSON object you could do this :
var json=[ { service_name: 'Instagram',
title: 'Instagram: “:point_right: Real people, making real products from real plants, using their actual hands to put them in boxes that show up on your doorstep.…”',
text: '36 Likes, 2 Comments - “:point_right: Real people, making real products',
ts: '1523497358.000299' }];
var rep = JSON.stringify(json).replace(/(“)(:[^:]+:)/g, '$1');
var New = JSON.parse(rep);
console.log(New);
Try this :
// JSON Object
var jsonObj = [{
"service_name": "Instagram",
"title": "Instagram: “:point_right: Real people, making real products from real plants, using their actual hands to put them in boxes that show up on your doorstep.…”",
"text": "36 Likes, 2 Comments - “:point_right: Real people, making real products",
"ts": "1523497358.000299"
}];
// Replace :point_right: with blank string.
jsonObj.map(obj => {
obj.title = obj.title.replace(":point_right: ", "");
obj.text = obj.text.replace(":point_right: ", "");
return obj;
});
// Output
console.log(jsonObj);
As part of an assignment for uni i've been asked to write a question worth 10 marks and then write a solution and marking scheme for said question.
This is my question;
Write a program that will store the top ranking fighters of 3 weight divisions in the UFC (using the following data);
-Featherweight; Connor McGregor, Jose Aldo, Frankie Edgar, Max Holloway, Anthony Pettis.
-Lightweight; Connor McGregor, Khabib Nurmagomedov, Tony Ferguson, Eddie Alvarez, Rafael dos Anjos.
-Light heavyweight; Daniel Cormier, Anthony Johnson, Alexander Gustafsson, Ryan Bader, Glover Teixiera.
Prompt the user to enter the name of a weight division in the UFC and return the ranking the the format;
Current Champion is ….
1st contender is …..
2nd contender is ……
Etc.
So far in my solution for the questioni have had the user enter the name of a weight division, however i now have the problem of trying to use that specific variable in a loop.
This is my code so far;
//Declaration of the arrays to store the ranking of the weight divisions;
var featherweight = ["Connor McGregor", "Jose Aldo", "Frankie Edgar", "Max Holloway", "Anthony Pettis"];
var lightweight = ["Connor McGregor", "Khabib Nurmagomedov", "Tony Ferguson", "Eddie Alarez", "Rafael dos Anjos"];
var lightHeavyweight = ["Daniel Cormier", "Anthony Johnson", "Alexander Gustafsson", "Ryan Bader", "Glovier Teixiera"];
//Declaring the output variable to store and add to what will be output before it is displayed;
var output = "";
//Variable to store the user input and a prompt to recieve the users input;
var userInput = prompt("Please enter the name of a weight devision you would like to see the rankings off. \n Options are; \n - featherweight \n - lightweight \n - lightHeavyweight");
//loop that will continue adding items to the output for the length of the array that the user has asked to see.;
for (var i = 0; i < )
Help is greatly appreciated, and thanks in advance!
Before the loop you should have chained if statements:
var chosenArray;
if (input === "x")
{
chosenArray = xArray;
}
elseif (input === "y")
{
chosenArray = yArray;
}
...
else
{
// should print that the input is unknown
}
// should use chosenArray for loop
I'm loading json file from database with two fields words and grade. Each word is graded for example true has 1 while lie has -1. Then i take input from text filed and i need to grade it based on grades from JSON file and then calculate score by summarizing the grades, but i just can't seem to find the way to do that. Words that are not in file are not being calculated.
I tried string.search match but it's to complicated and in the end i couldn't get result the way i wanted. I tried array searches same thing. I searched for on line solution, but no one has done anything similar so i can't copy it.
JSON
[
{"word":"true","grade":1},
{"word":"hate","grade":-1},
{"word":"dog","grade":0.8},
{"word":"cat","grade":-0.8}
]
String
"Dogs are wonderful but i prefer cats, cats, i can not lie although dog is a true friend".
The first thing I'd do is turn your JSON data into a map which can easily be searched - key would be the word, and value the grade:
var json = [
{"word":"true","grade":1},
{"word":"hate","grade":-1},
{"word":"dog","grade":0.8},
{"word":"cat","grade":-0.8}
];
var map = json.reduce(function(p,c){
p.set(c.word.toLowerCase(),c.grade);
return p;
}, new Map());
console.log(...map);
Then, its just a case of splitting your string, whilst also calculating the total score - again reduce can be used
var json = [
{"word":"true","grade":1},
{"word":"hate","grade":-1},
{"word":"dog","grade":0.8},
{"word":"cat","grade":-0.8}
];
var map = json.reduce(function(p,c){
p.set(c.word.toLowerCase(),c.grade);
return p;
}, new Map());
var input = "Dogs are wonderful but i prefer cats cats i can not lie although dog is a true friend";
var score = input.split(' ').reduce(function(p,c){
var wordScore = map.get(c.toLowerCase()) || 0;
return p + wordScore;
},0);
console.log(score);
Note that I have manually removed punctuation in the above input - I'll leave that as an exercise for you.
Also note that "cats" != "cat" so some of your words wont be found!
Let's first think of the algorithm. Two options:
Search and count the input string as many times as number of words in your JSON, or
Check each word in your input string against the JSON contents.
Since the JSON length is known and (I presume) shorter than the possible input string, I would tend to prefer option 2.
Now, after selecting option 2, you need to split the input string into words and create an array containing one word each entry of the array.
You can achieve this using the mystring.split(" ") method. This, of course, does not take into account punctuations, but you can handle this using the same method.
Now, you can add to each entry in your JSON a field to count the number of appearances of each entry in the JSON within the string.
Finally, you sum the product of the counters and the grade.
console.log((function(rules, str) {
var sum = 0;
Array.prototype.forEach.call(rules, function(rule) {
var match = str.match(rule.regexp);
match && (sum += str.match(rule.regexp).length * rule.grade);
console.log([rule.regexp, match&&match.length, rule.grade, match&&match.length * rule.grade, sum]);
});
return sum;
})([{
"regexp": /true/g,
"grade": 1
}, {
"regexp": /hate/g,
"grade": -1
}, {
"regexp": /dog/g,
"grade": 0.8
}, {
"regexp": /cat/g,
"grade": -0.8
}], "Dogs are wonderful but i prefer cats, cats, i can not lie although dog is a true friend"));
i use regexp rather than string, u can use string and convert to regex at run time, hope this would help
I have a script built to grab a quote from an array at random, and display it.
I'm trying to format it so it would split the quote and the author like so:
"Insert quote"
Name of person saying Quote
I've tried using split with \n and <br /> and nothing works, even in an alert.
here is my code:
//Initalize the array
var quotes = [];
//Insert data into the array
quotes[0] = "It doesn't matter how many times you have failed, you only have to be right once." + "Mark Cuban";
quotes[1] = "Video games are bad for you? That's what they said about rock n' roll." + "Shigeru Miyamoto";
quotes[2] = "I'd like to be known as the person who saw things from a different point of view to others." + "Shigeru Miyamoto";
quotes[3] = "Stay hungry, stay foolish, stay crazy." + "Steve Jobs";
quotes[4] = "The future was uncertain, absolutely, and there were many hurdles, twists, and turns to come, but as long as I kept moving forward, one foot in front of the other, the voices of fear and shame, the messages from those who wanted me to believe that I wasn't good enough, would be stilled." + "Chris Gardner";
quotes[5] = "Running a start-up is like eating glass. You just start to like the taste of your own blood." + "Sean Parker";
quotes[6] = "I used to drink cristal, the muh'fucker's racist. So I switched gold bottles on to that Spade shit" + "Shawn Carter (Jay Z)";
quotes[7] = "I think it's better to let my work do the talking" + "Shigeru Miyamoto.";
quotes[8] = "Success is a lousy teacher. It seduces smart people into thinking they can't lose." + "Bill Gates";
quotes[9] = "We need to reengineer companies to focus on figuring out who the customer is, what's the market and what kind of product you should build." + "Eric Ries";
quotes[10] = "I have no friends and no enemies - only competitors." + "Aristole Onassis";
quotes[11] = "Working 24 hours a day isn't enough anymore. You have to be willing to sacrifice everything to be successful, including your personal life, your family life, maybe more. If people think it's any less, they're wrong, and they will fail." + "Kevin O'Leary";
quotes[12] = "My hope is to the see the benefits of my labour spread out in the community." + "W. Brett Wilson";
quotes[13] = "I'm not here to make friends; I'm here to make money." + "Kevin O'Leary";
quotes[14] = "Good artists copy, great artists steal" + "Pablo Picasso";
quotes[15] = "Welcome ladies and gentlemen to the eighth wonder of the world. The flow of the century, always timeless; HOV!" + "Shawn Carter (Jay Z)";
quotes[16] = "Today’s “best practices” lead to dead ends; the best paths are new and untried." + "Peter Thiel";
quotes[17] = "I believe life is an intelligent thing: that things aren't random." + "Steve Jobs";
quotes[18] = "Pretty? You mean like rainbows, unicorns, and sparkles?" + "Michelle Brown";
quotes[19] = ".....and for that reason, I'm OUT!" + "Mark Cuban";
//Splits the quote into two pieces, the quote and the person.
var quoteSplit = function (quotes) {
var split = quotes.split("+").replace("\n");
}
//Displays a quote from the array at random.
var displayQuote = quotes[Math.floor(20 * Math.random())];
document.write(displayQuote);
//END
When you're building your array, you are concatenating the quote with the author. So this:
quotes[0] = "It doesn't matter how many times you have failed, you only have to be right once." + "Mark Cuban";
Ends up with this string being set to quotes[0]
It doesn't matter how many times you have failed, you only have to be right once.Mark Cuban
And your split statement will not work, because the + is not included in the string. This isn't a great way of setting up your array, though. What happens if your quote contains the + symbol, for example?
A better way would be to create an object for each item:
quotes[0] = {
text: "It doesn't matter how many times you have failed, you only have to be right once.",
author: "Mark Cuban"
}
Then you can do:
var displayQuote = quotes[Math.floor(20 * Math.random())];
document.write(displayQuote.text + '<br>' + displayQuote.author);
It's seems that + sign is not in your string. The following code:
console.log("Today’s “best practices” lead to dead ends; the best paths are new and untried." + "Peter Thiel");
will return to you string
Today’s “best practices” lead to dead ends; the best paths are new and untried.Peter Thiel;
So, you just have to include + sig in your strings like that:
"Today’s “best practices” lead to dead ends; the best paths are new and untried.+Peter Thiel"
As Daniel A. White said in the comments section. You are considering + to be part of the string but you are in fact concatenating 2 strings on each index.
quotes[3] = "Stay hungry, stay foolish, stay crazy." + "Steve Jobs";
should be:
quotes[3] = "Stay hungry, stay foolish, stay crazy.+Steve Jobs";
Or you could use regex ( Unfortunately I can't provide a regex example right now ) but those are two of your possible options.
If you output any element of your array, you'll see that each entry is a single string with quote and person. Ex.
console.log(quotes[3]);
Stay hungry, stay foolish, stay crazy.Steve Jobs
That's because + concatenates when applied to strings.
As suggested in the comments, you could use split on punctuation marks, although that would break some of your quotes.
You could do something like
quotes[3]=["Stay hungry, stay foolish, stay crazy.","Steve Jobs"];
and output each element separately.
Try this:
var quotes = {
1: {
quote: 'Hello world.',
author: 'Test test'
},
2: {
quote: 'Hello world 2.',
author: 'Test test 2'
},
};
// Display random quote
function displayQuote(){
var key = Math.floor(Math.random() * Object.keys(quotes).length + 1);
return quotes[key].quote + ' ' + quotes[key].author;
};
document.write(displayQuote());