I am playing with some basic js I am just beginning to learn, so far I have the code below. I am trying to ask the user what their name is and then tell them if they share the same name as a racing driver (from my array driversNames).
If they have the same name as a racing driver it would tell them they do, if not it would tell them they don't. However I have a feeling I have something wrong here: if (yourName === driversNames) but I cannot figure it out.
It doesn't matter what I enter into the prompt, it always says sorry you don't have the same name.
var driversNames = ["Lewis", "Fernando", "Sebastian", "Jenson", "Daniel"]
for (var i = 0; i < driversNames.length; i++) {
console.log(driversNames[i] + " " + "is a drivers name");
}
var yourName = prompt("What is your name?")
console.log("Your name is" + " " + yourName)
if (yourName === driversNames) {
console.log("Awesome" + " " + yourName + " " + "you share the same name as a Formula 1 driver!")
} else {
console.log("Sorry" + " " + yourName + " " + "you don't have the same name as any Formula 1 drivers")
}
You made one mistake in this line if (yourName === driversNames).
It doesnt compare your name with names from driversNames. The most easiest way: its use indexOf method. So this line should be like below
if (driversNames.indexOf(yourName) > -1) //Get Name otherwise no
And jsfiddle example for you, also indefOf link
Thanks
You are comparing a string to an array, so the comparison will return false. You have a few options to fix this though - I'll explain using a loop to check each string, and using indexOf.
Loop: You need to loop through each element in the driversNames array and compare each one. This is the manual way.
var sameName = false; //flag to keep track of if name matches or not
driversNames.forEach(function(name) { //loop through each name in driversNames
if(yourName === name) { //compare your name to driver name
sameName = true; //if match, set flag to true
}
}); //loop ends here
if(sameName) { //if flag is true, a name matched
console.log("Awesome" + " " + yourName + " " + "you share the same name as a Formula 1 driver!"); //Console log success statement
} else { // else, no name matched
console.log("Sorry" + " " + yourName + " " + "you don't have the same name as any Formula 1 drivers"); //console log fail statement
}
IndexOf: This method uses less lines of code, but isn't compatible on all browsers - I believe anything under IE8 will break when using this for example. But if compatibility isn't an issue, it looks like this:
if (driversNames.indexOf(yourName) > -1) { //indexof returns -1 for no match, and a number for match
console.log("Awesome" + " " + yourName + " " + "you share the same name as a Formula 1 driver!"); //console log success statement
} else {
console.log("Sorry" + " " + yourName + " " + "you don't have the same name as any Formula 1 drivers"); //console log fail statement
}
indexof is a little more elegant, although easy to forget the compatibility issue. Code is commented but just to explain it: Arrays have a method you can call, called indexOf() which takes a parameter. This method will then check if that parameter is in the array and if it is, return a value which is it's position in the array. If it isn't in the array, it will return -1.
Related
I've just started learning how to code in JS and I wanted to make a program that greets the user after he fills the information needed age and name.
I added a loop that checks if provided data typed in the prompt is a number but it seems to go on infinitely, like the value was always wrong and the loop looped itself over and over even if the value was right (of course after I firstly typed in the wrong value).
The best part is when I display the typeof value it shows it's right and wrong at the same time.
alert("Hi this site is only accsesable by pepole above an age of 18")
let usersAge = prompt("How old are you?");
usersAge = Number(usersAge);
while (Number.isNaN(usersAge)) {
let usersAge = prompt("type in the correct value?");
}
if (usersAge >= 18) {
let userName = prompt("cool,what is ur name")
toString(usersAge)
console.log("wassup" + " " + userName + " " + "with age of" + " " + usersAge)
} else {
console.log("sorry ur age is to low for us to display this website")
};
console.log(typeof usersAge)
console.log(usersAge)
Console output:
sorry ur age is to low for us to display this website
"number"
NaN
The first issue is because you're redefining usersAge within the while block, which affects the outcome of that loop. Remove the let keyword there.
The other issue is that you're comparing strings to integers in some cases. Cast all values to the same type before comparison.
With those issues addressed your code works:
alert("Hi this site is only accsesable by pepole above an age of 18")
let usersAge = parseInt(prompt("How old are you?"), 10);
while (Number.isNaN(usersAge)) {
usersAge = parseInt(prompt("type in the correct value?"), 10);
}
if (usersAge >= 18) {
let userName = prompt("cool,what is ur name")
toString(usersAge)
console.log("wassup" + " " + userName + " " + "with age of" + " " + usersAge)
} else {
console.log("sorry ur age is to low for us to display this website")
};
console.log(typeof usersAge)
console.log(usersAge)
However putting a prompt() in a potentially infinite loop is a really bad design choice. The kind which will infuriate your users and get your site blacklisted.
A better approach would be to validate the input and if it's invalid then you should give the user the choice to cancel out of the loop and leave your site. Right now you're forcing the user to enter an age before they can leave.
Hi my friend to fix your problem you need to not use let because you use it once.
I'm going to give you the right syntax for your problem :
alert("Hi this site is only accsesable by pepole above an age of 18");
let usersAge=prompt("How old are you?");
usersAge = Number(usersAge);
while(Number.isNaN(usersAge) || usersAge === null || usersAge === '') {
usersAge= prompt("Enter your age")
}
{
if( usersAge >= 18){
let userName = prompt("cool,what is ur name");
toString(usersAge)
console.log("wassup" + " " + userName + " " + "with age of" + " " + usersAge)
}
if( usersAge < 18){
console.log("sorry ur age is to low for us to display this website");
} else{
usersAge = prompt("type in the correct value?")
}
}
I hope your problem was solved.
Okay so i have started learning javascript from the book Beginning Javascript 5th ed, just confused by a js script
function getCookieValue(name) {
var value = document.cookie;
var cookieStartsAt = value.indexOf(" " + name + "=");
if (cookieStartsAt == -1) {
cookieStartsAt = value.indexOf(name + "=");
}
if (cookieStartsAt == -1) {
value = null;
} else {
cookieStartsAt = value.indexOf("=", cookieStartsAt) + 1;
var cookieEndsAt = value.indexOf(";", cookieStartsAt);
if (cookieEndsAt == -1) {
cookieEndsAt = value.length;
}
value = unescape(value.substring(cookieStartsAt,
cookieEndsAt));
}
return value;}
My question is how does the indexOf operator works here( i know how it works and used it previously) ??
The above program is defined below by the book which goes as :
The first task of the function is to get the document.cookie string and store it in the value variable
var value = document.cookie;
Next, you need to find out where the cookie with the name passed as a parameter to the function
is within the
value string. You use the inde x Of() method of the String object to find this
information, as shown in the following line:
var cookieStartsAt = value.indexOf(" " + name + "=");
The method will return either the character position where the individual cookie is found or ‐1 if no
such name, and therefore no such cookie, exists. You search on
" " + name + "=" so that you don’inadvertently find cookie names or values containing the name that you require. For example, if you
have
xFoo, Foo, and yFoo as cookie names, a search for Foo without a space in front would match
xFoo first, which is not what you want!
What the just just happened here?? How did they achieve the location of the name using indexOf() ?? please explain ? I couldn't understand the xfoo,foo,yfoo example ?? Looking for a simpler example.
document.cookie contains a string like cookiename=cookievalue
indexOf is getting the position of the begining of the value part of the cookie
var cookieStartsAt = value.indexOf("cookiename=");
That allows you to use that number to get the value portion of the string with substring()
I've decided to just try again from the start since I'm a bit more awake now and go over building this step by step. i've looked at some of the answers and there seems to be many ways one could go about this. I'm trying to do this using what I've learned so far. I've learned about variables, basic functions, objects, arrays, 'this' and the push method. I know for, while, do while, for in loops, though the for loop is the one I understand the best.
Here is my new approach to building this, I know it's unnecessarily long but I want to be able to get a basic understanding of how to piece the different things I've learned together in a very simple way. This is more about learning how to go about building simple programs. Then I would proceed in fine-tuning the program to make it more concise and clever. If you could have a look and tell me how I would proceed with what I've got so far...
Here is the code, Ideally I want to run a function when there's a new 'visitor' that asks for their name and number. Then create a new 'customer' object with the given name and number and push it to a 'visitors' array. once I've successfully figured that out I would use loops to check the array if the visitor is new or not, and update their number of visits everytime they come.
//array that will contain 'Customer' objects
var visitors = [john];
//Customer object
function Customer(name, phonenumber){
this.name = name;
this.phonenumber = phonenumber;
//will eventually add a "visits" method logging number of visits
}
var john = new Customer("john smith", "333");
//visitor funtion that runs everytime there is a new visitor
var visitor = function(){
//visitor does not have a set name or number yet
var userNumber = "variable userNumber is currently equal to " + 0;
var userName = "variable userName is currently set to " + undefined;
console.log(userName, userNumber);
//ask for visitor name and number
var askNumber = prompt("type your number");
var askName = prompt("what is your name?");
//store user name and number in two variables
var userNumber = "variable 'userNumber' is now equal to " + askNumber;
var userName = "variable userName is now set to " + askName;
//print out the new variables
console.log(userNumber);
console.log(userName);
//print who the phone number belongs to, this lets me see that the above code worked correctly
var userNumber = askNumber;
var userName = askName;
console.log("Phone number " + userNumber + " belongs to " + userName);
//make new customer object with the given name and number
var userNumber = new Customer();
userNumber.name = askName;
userNumber.phonenumber = askNumber;
console.log("properties of " + userNumber);
};
the last bit returns "properties of [object, object]" why?
Not only did you confuse yourself, but you crashed the browser! :-)
(The for loop never terminates because you push a new value to the list on every iteration.)
I could tell you what's wrong with the code in more detail, but you'll learn a lot more if you chase it down yourself. So what you need now is to learn the art of debugging.
Add a debugger statement at the beginning of your test() function:
var list = ["111", "222", "333", "444", "555", "666"];
var test = function(input){
debugger;
var info = prompt("hi " + input + " what is your name?");
for(i=0; i< list.length; i++){
if( info === list.length[i]){
console.log(list[i]);
}
else{
list.push(info);
}
console.log(list);
}
}
Now run test() and it will stop in the debugger at that statement. Look at the different panels in the debugger - you can view your variables and other stuff. Find the place where it has controls to let you step through your code. Single-step through the code and look at the variables as you go. You will soon discover what the problems are. In most browsers there are also keyboard shortcuts to let you step through the code more easily.
If you use Chrome, here is an introduction to the Chrome DevTools. There are similar tutorials for the other browsers too.
heres an algorithm :
Use an object to store the user no. and the count. like :
{"222":"3","444":"1"}
this means 222 has visited 3 times and 444 visited once. now every time a user checks in:
see if the key with the user's number exists, if yes increment the count. if no, add a new entry with count = 1.
check if the number is 5, if yes get free coffee and reset count to zero. skip if no.
I would solve the problem by storing the visit count in a dictionary that maps each customer's ID to the number of times they have visited. The dictionary is initially empty. When you look up an ID in the dictionary for the first time, you'll get undefined, which tells you that you must initialize the value.
The following demonstration has a couple of buttons that you can use to make Alice or Bob visit the shop. Click on the blue button at the bottom to start the demo.
function message(s) { // Simple output for a code snippet.
document.getElementById('display').innerHTML += s + '<br />';
}
var coffeeCount = {}; // Stores the number of visits by each customer.
function customerVisit(id) { // Called when a customer visits.
if (coffeeCount[id] === undefined) { // Check for first visit.
coffeeCount[id] = 0; // Initialize the visit count.
}
var count = ++coffeeCount[id]; // Increment the visit count.
message(id+': '+count+' visit'+(count == 1 ? '' : 's'));
if (count % 5 == 0) { // Check for free coffee.
message('→ Free coffee for customer '+id+'!');
}
}
<button onclick="customerVisit('Alice')">Alice</button>
<button onclick="customerVisit('Bob')">Bob</button>
<div id="display"></div>
Try including utilization of input elements; set visits count as value of property id, info at object list; call test with value of input element : id ; or at prompt : info . At five visits , display coffee , reset value of id to 0.
var list = {
"111": 0,
"222": 0,
"333": 0,
"444": 0,
"555": 0,
"666": 0
};
var test = function test(id) {
coffee.innerHTML = "";
var info;
if (id.length > 0 && !/^(\s)/.test(id)) {
if (list.hasOwnProperty(id)) {
++list[id];
} else {
list[id] = 1;
}
info = confirm("hi " + id + " this is your " + list[id] + " visit");
} else {
info = prompt("hi, please enter an id");
if (!!info && !/^(\s)/.test(info) && list.hasOwnProperty(info)) {
list[info] = 1;
confirm("hi " + info + " this is your " + list[info] + " visit");
} else {
info = prompt("hi, please input a different id");
if (!!info && !/^(\s)/.test(info) && !list.hasOwnProperty(info)) {
list[info] = 1;
confirm("hi " + info + " this is your " + list[info] + " visit");
}
};
alert("please try a different id")
};
for (var id in list) {
if (list[id] === 5) {
alert("hi " + id + ", thanks for visting " + list[id] + " times");
coffee.innerText = "☕";
list[id] = 0;
break;
}
};
console.log(list);
};
var inputs = document.querySelectorAll("input");
var coffee = document.getElementById("coffee");
coffee.style.fontSize = "5em";
inputs[1].onclick = function(e) {
test(inputs[0].value)
};
<input type="text" placeholder="please enter id" value="" />
<input type="button" value="click" />
<div id="coffee"></div>
n is number of costumer
Initially array is [0,0,0,.....n times]
All values are 0 because no costumer has visited the shop.
For n=5 array would look like
var a=[0,0,0,0,0];
1)To solve this problem in array.
2)Suppose we have array of size n.
3)then index of the array will be 0...n-1
4)So we can map id of costumer to the index.
5)And value will keep count of the number of visit for the index.
6)a[5]=11; here 5 is index and 11 is value
7)For our problem if customer with id i we increment a[i]=a[i]+1 if he visits .
8) Then we can check
if(a[i]+1 === 5) {
console.log("Custumer "+ i + " get a free coffee");
a[i]=0;
}
else {
a[i]=a[i]+1;
}
I've decided to just try again from the start since I'm a bit more awake now and go over building this step by step. i've looked at some of the answers and there seems to be manyt ways one could go about this. I'm trying to do this using what I've learned so far. I've learned about variables, basic functions, objects, arrays, 'this' and the push method. I know for, while, do while, for in loops, though the for loop is the one I understand the best.
Here is my new approach to building this, I know it's unnecessarily long but I want to be able to get a basic understanding of how to piece the different things I've learned together in a very simple way. This is more about learning how to go about building simple programs. Then I would proceed in fine-tuning the program to make it more concise and clever. If you could have a look and tell me how I would proceed with what I've got so far...
Here is the code, Ideally I want to run a function when there's a new 'visitor' that asks for their name and number. Then create a new 'customer' object with the given name and number and push it to a 'visitors' array. once I've successfully figured that out I would use loops to check the array if the visitor is new or not, and update their number of visits everytime they come.
//array that will contain 'Customer' objects
var visitors = [john];
//Customer object
function Customer(name, phonenumber){
this.name = name;
this.phonenumber = phonenumber;
//will eventually add a "visits" method logging number of visits
}
var john = new Customer("john smith", "333");
//visitor funtion that runs everytime there is a new visitor
var visitor = function(){
//visitor does not have a set name or number yet
var userNumber = "variable userNumber is currently equal to " + 0;
var userName = "variable userName is currently set to " + undefined;
console.log(userName, userNumber);
//ask for visitor name and number
var askNumber = prompt("type your number");
var askName = prompt("what is your name?");
//store user name and number in two variables
var userNumber = "variable 'userNumber' is now equal to " + askNumber;
var userName = "variable userName is now set to " + askName;
//print out the new variables
console.log(userNumber);
console.log(userName);
//print who the phone number belongs to, this lets me see that the above code worked correctly
var userNumber = askNumber;
var userName = askName;
console.log("Phone number " + userNumber + " belongs to " + userName);
//make new customer object with the given name and number
var userNumber = new Customer();
userNumber.name = askName;
userNumber.phonenumber = askNumber;
console.log("properties of " + userNumber);
};
the last bit returns "properties of [object, object]" why?
I will give you a short function to check how many times a specific value is at the array:
function countHowManyTimesAValueIsOnArray(arr, valueToCheck){
return arr.filter(function(arrayValueToCompare){
return arrayValueToCompare === valueToCheck;
}).length
}
Attention for the use of '===' instead of '=='. This will compare the value considering its type. 222 will not be found as "222"
No need to complicate things here's an simple way, just add a count function that search how many times user has enter
var list = ["111", "222", "333", "444", "555", "666"];
var test = function(input){
var info = prompt("hi " + input + " what is your name?");
var check=0;
for(i=0; i< list.length; i++){
if( info === list[i]){
check=1;
break;
}
}
list.push(info);
if(check==1){
count(info);
}
}
function count(info){
var count=0;
for(i=0; i< list.length; i++){
if(list[i]===info)
count++;
}
console.log(count);
}
}
I am very new to learning both Javascript and Jquery.
In the website I am creating I am trying to insert a Javascript if statement and a for loop in a line of JQuery. The last confirm does not run. I suspect it is the if statement that is causing the issue. How can I fix this? Here is how my code looks like.
$(document).ready(function() {
$(".button3").click(function() {
var lastname = $('#lastnameresponse').val();
confirm("You're last name is" + " " + lastname);
if (userResponse = "girl") {
for (var i = 0; i <= girlnames.length; i++) {
confirm("Your future daughter's name is" + " " + random + " " + randomagain + " " + lastname);
})
});
There's a lot that doesn't make much sense with your code.
First, what is userResponse? Where does this get defined and where is it set? Have you verified under a debugger that it is indeed equal to "girl"?
Second, you probably meant to use a comparison equals not an assignment equals here:
if (userResponse = "girl") { // This should be ==
However, this should not prevent the block from running. In fact, it will force the block to always run since "girl" is true-ish.
Third, what is girlnames? Is it an array? Where is this defined? Have you verified it indeed contains valid items?
Lastly, I believe your for loop is incorrect:
for (var i = 0; i <= girlnames.length; i++) {
Should be:
for (var i = 0; i < girlnames.length; i++) {
Arrays start at 0, thus girlnames[girlnames.length] is not a valid item.
However, considering you don't use the i variable in your loop anywhere, again this should not actually cause any errors.
I would step through your code line by line using a script debugger (usually F12 in modern browsers) and set a break point at:
var lastname = $('#lastnameresponse').val();
Then verified each line is behaving correctly. If that still doesn't work, you'll need to post more of your code so we can get a better idea of what's going on.
UPDATE:
Based on your comment:
Here is where the userResponse variable is defined:
$(document).ready(function(){ $("#girlimg").click(function() { var
userResponse = prompt("Confirm the gender you selected").toLowerCase;
$('html, body').animate({ scrollTop: $(".LastName").offset().top },
2000);
It seems that userResponse gets declared within the click handler for the #girlimg tag:
$("#girlimg").click(function() {
// Everything declared here is local to this function
var userResponse = confirm(); // local variable
});
Thus, it would not be accessible in the click handler for .button3. You'll need to declare userResponse in a scope that is accessible to both functions. Perhaps global (this is frowned upon in JavaScript) or within your $(document).ready() code, provided both click event handlers are defined within that block.
First: it's Your not You're :)
Secondly, userResponse is undefined. Maybe it's defined somewhere else.
For comparison, use == operator.
Are you sure is that what you want to do? I see you also have confirm there.
Use confirm like this:
$(".button3").click(function() {
var lastname = $('#lastnameresponse').val();
// confirm() returns true or false, depending on the clicked button
is_confirmed = confirm("You're last name is" + " " +lastname);
if (true == is_confirmed) {
for (var i = 0; i <= girlnames.length; i++) {
confirm ("Your future daughter's name is" + " " + random + " " + randomagain + " " + lastname);
}
}
});
girlnames is also not defined here (maybe it's somewhere else). Same for random and randomagain
As for writing JavaScript "in" jQuery: there is no such question. jQuery is a library written in Javascript that provides useful functions to ease development.
Following statement does not contain a proper JavaScript Comparison Operator
equals is written ==
if (userResponse = "girl") {
for reference look here
you forgot to close some arrows, any way when you put :
if (userResponse ="girl"){...}
you set userResponse variable to "girl", and that passes the value to the variable only
to check in the userResponse is equal to "girl" you should put
if (userResponse =="girl")
your final code will look like this
$(document).ready(function(){
$(".button3").click(function() {
var lastname = $('#lastnameresponse').val();
confirm("You're last name is" + " " +lastname);
if (userResponse ="girl") {
for (var i = 0; i <= girlnames.length; i++) {
confirm ("Your future daughter's name is" + " " + random + " " + randomagain + " " + lastname);
}}}
)
});
p.s:you forgot to close too many arrows
my name's Mike and my question is two-fold:
How can I access the objects in my array so that they properly appear in my question prompt, and
How can I access the properties of the randomely selected object in an if/else statement?
I'm trying to make a simple flashcard program to help me memorize different kinds of sound equipment. The list of equipment is large but I'm only including three different kinds to keep this example simple. I want each object to have two properties: answer and desc. This first part defines three objects, places them in an array, creates a variable for picking one of the array items randomely, and another variable for prompting the user for an answer:
var newFlash = function() {
var A827 = {
answer: "T",
desc: "Multitrack Tape Recorder"
};
var LA2A = {
answer: "O",
desc: "Classic Leveling Amplifier"
};
var SonyC800G = {
answer: "M",
desc: "Tube Condenser Microphone"
};
var list = [A827, LA2A, SonyC800G];
var rand = Math.floor(Math.random() * list.length);
var question = prompt("What kind of equipment is " + list[rand] + "?");
};
Now, if I make my three items in my array all strings, they show up no problem in the question prompt correctly replacing list[rand] with the appropriate array item. However, using objects in my array, my prompt says "What kind of equipment is [object Object]?.
My end goal is for the user to enter the appropriate one- or two-letter response (M for Microphone, C for Console, O for Outboard Gear, T for Tape Machine, S for Software, and CH for Computer Hardware) where upon entering the successful letter(s) yields an alert that displays both the object's answer and desc. My n00b instinct tells me this second part should be an if/else statement in the form of
if (question == list[rand.answer]) {
alert("Correct, Answer: " + list[rand.answer] + ", a " + list[rand.desc] + "!");
}
else {
alert("Wrong, try again.");
}
but I'm very certain that this isn't the right way to access these object properties.
So, again, my question has two parts:
How can I access the objects in my array so that they properly appear in my question prompt, and
How can I access the properties of the randomely selected object in an if/else statement?
I'm sure some piece of logic is escaping me. Thanks for reading.
You want to use var question = prompt("What kind of equipment is " + list[rand].desc + "?");. list[rand] will yield you an object which has the structure {answer: "", desc: ""}, so you need to additionally access the description in your code.
Similarly, you want:
if (question == list[rand].answer) {
alert("Correct, Answer: " + list[rand].answer + ", a " + list[rand].desc + "!");
}
else {
alert("Wrong, try again.");
}
To access the property of an Object in Javascript you use dot notation, as is common with many languages that have Objects. list is an array of Objects, so when you type list[rand] you are returning one of those Objects. Once you have an Object, you simply need to use the dot notation to access whatever property it is you require, in this case either desc or answer.
So instead of
var question = prompt("What kind of equipment is " + list[rand] + "?");
try
var question = prompt("What kind of equipment is " + list[rand].desc + "?");
Placing the property you are trying to access outside the bracket. This solves your second question as well, simply change:
if (question == list[rand.answer]) {
alert("Correct, Answer: " + list[rand.answer] + ", a " + list[rand.desc] + "!");
to:
if (question == list[rand].answer) {
alert("Correct, Answer: " + list[rand].answer + ", a " + list[rand].desc + "!");
this fiddle will help demonstrate.