How to count number of times an item is in an array - javascript

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);
}
}

Related

How to send mails with some functionality using google apps script

I am new to Google Apps Script. I have a sheet that collects some "Order Number" from form submit. I want to send mails through an event (On form submit) from my spreadsheet. The form will serve an order number. When the form is submitted, it will match the older submitted order numbers throughout the whole column. If it got matched once, the mail won't be sent. If it doesn't match then it will send a mail to the email address next to the order number.
The email address will come from another sheet on the same spreadsheet using VLOOKUP. I managed to do this.
Sorry if I make any mistake with my English.
Edit:
I tried map() , filter() , indexOf() these methods. But I too new with this.
function search(){
var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Copy of orderStatus");
var lr = ss.getLastRow() - 1;
var keyword = ss.getRange("H5").getValue();
var dataSource = ss.getRange(2, 2, lr, 1).getValues();
var mapped = dataSource.map(function(r){
return r[0]});
var showPos = mapped.indexOf(keyword) + 2;
var getMail = ss.getRange(showPos, 4).getValue();
var filted = mapped.filter(filterlogic);
}
var filterlogic = function(r){
if(r !== "zil20200010"){
return true;
} else {
return false;
}
}
On form submit, select the column (range) where you store all the order numbers and create a TextFinder and store it in a variable using the createTextFinder(findText) method for the specified range.
Get the TextFinder from the previous step and search the order number using the findNext() method.
If findNext() returns null then move to the next step. else, do nothing.
Get the email address to which you plan to send the order number.
After having the email address, use the sendEmail(recipient, subject, body, options) method to send the email. If you'd like, you can use HTML in the body to make it more professional.
For additional information, read:
the reference guide on creating TextFinders,
the reference guide on finding text using a TextFinder,
and the reference guide on GmailApp.
Sample code:
// imagine you store all the order numbers in column C, starting from row 2 to the last row in the column:
var emailRecipient = test#test.com;
var ordernumber = 123;
var RangeToSearch = sheet.getRange(2,3,sheet.getLastRow());
var TextFinder = RangeToSearch.createTextFinder(ordernumber);
var found = TextFinder.findNext();
if (found == null) {
MailApp.sendEmail({
to: emailRecipient,
subject: "New Order! Order Number: " + ordernumber,
htmlBody: html
});
}
First of all, thanks to all of you who helped me to reach this point. I found the solution to my problem after some "trial and error". I wanted to limit sending emails.
This code takes the Range. Get its values in an array. I mapped that array to act as a string. Then I added .pop() to that string, it removes our last/newly submitted data in that range. Then I used .includes() method to search my value in the mapped array, and assigned it to a variable called final (just came to my mind). This variable returns true/false depending on search results. If the order number does not exist then it returns false. After that, we set an if statement to execute our mailing function. If our order number does not match and return final as false our mailing function happens. Else it does nothing (means no email sents). And that's it!
Here is the code that solved my problem
function orderStatus(e) {
try {
var theirMail, subject, message;
var ourName, theirName;
var sSheet, orderNum, cosmetics, orderSts, phNum, lr,dataSource, mapped, final;
ourName = "My Company Name";
orderNum = e.namedValues["Order Number"].toString();
sSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("orderStatus");
lr = sSheet.getLastRow() - 1;
dataSource = sSheet.getRange(2, 2, lr).getValues();
mapped = dataSource.map(function(r){
return r[0].toString()});
mapped.pop();
final = mapped.includes(orderNum);
orderSts = sSheet.getRange(sSheet.getLastRow(),1).getValue();
theirMail = sSheet.getRange(sSheet.getLastRow(),4).getValue();
theirName = sSheet.getRange(sSheet.getLastRow(),5).getValue();
phNum = sSheet.getRange(sSheet.getLastRow(),6).getValue();
subject = "Order status notification from " + ourName + " to " + theirName;
if (final == false){
message =
"<div style='text-align: left; padding-left: 30px;'><h2>Dear <b>" + theirName +
",</b></h2><p>Your order no is <b><span style='font-size: 14px;'>" + orderNum +
"</span>.</b> <b><span style='font-size: 14px;'>Your order has been processed.</span>" +
"</b></p><p>We packaged your order and dropped it to the logistics. You will recieve phone call on <b><span style='font-size: 14px;'>" + phNum +
"</span></b> from logistics.<br>Thanks for purchasing from <b><span style='font-size: 14px;'>" + ourName +
"</span></b>.</p><p>Best regards,<br><b><span style='font-size: 14px;'>"+ourName+"</span></b></p></div>"+
"<p style='text-align: center;'><br><b>For further information please visit our facebook page <a href='https://www.facebook.com/' target='_blank' rel='noopener'>"+ourName+"</a>.</b></p><hr />";
textbody = message.replace("<br>", "\n\n");
cosmetics = {name: ourName, htmlBody: message};
MailApp.sendEmail(theirMail, subject, message, cosmetics);
}
}
catch (e) {
Logger.log(e.toString());
}
}

Using JS to sum a column of values from an external text file containing donation histories of a db of donors

I need some assistance figuring out how to sum a column of dynamic totals that could be a positive or negative dollar amount, or an indication of stock shares.
I have a tab-delimited text file of donor contributions for that I am matching up against a CSV file of other related customer data that I am using to create a statement letter which will show a "donation history" of a particular donor. Each donor has a different amount of donations, and to complicate things, the column of data for a particular donation record could show either "$1,000.00" or "($1,000.00)" or "2 Shares APPL". The number with the parentheticals is of course, representing a negative number.
At the end of this column, I need to show a string that will read either "Total: $1,000.00," or if any of the donation history contains a donation record that included shares of stock the returned string will simply read, "$1,000.00 & Stock."
I have been racking my brain trying to come up with the JS rule that can achieve this. I have the JS rule that is generating the donation history correctly, but summing the donation amount column is causing me to go crazy...
Here is the JS for generating my donation history list in the letter (this seems to be working fine):
var contributionList = new ExternalDataFileEx("/~wip/248839 Frontiers/Master Data/Double Data proof.txt", "\t");
var donor_id = Field("Supporter");
var lb = "<br>\n";
var matches = new Array();
for (var i = 0; i <= contributionList.recordCount; i++) {
var idVariable = contributionList.GetFieldValue(i, "Supporter");
var dateVariable = contributionList.GetFieldValue(i, "Donation Date");
var ministryVariable = contributionList.GetFieldValue(i, "Ministry Designation");
var giftVariable = contributionList.GetFieldValue(i, "Donation Amount");
var tsSettings = "<p tabstops=19550,Right,,;29600,Left,,;>";
var ts = "<t>";
if (donor_id == idVariable)
matches.push(tsSettings + dateVariable + ts + giftVariable + ts + ministryVariable);
}
//return matches;
return matches.join(lb);
Now here is the JS code that is not working just fine. I am trying to tally the donation amount column, it only returns "Total: $0.00 & Stock" every time (I have tried to explain my thought process via comments):
var contributionList = new ExternalDataFileEx("/~wip/248839 Frontiers/Master Data/Double Data proof.txt", "\t");
var donor_id = Field("Supporter");
for (var i = 0; i <= contributionList.recordCount; i++) {
var idVariable = contributionList.GetFieldValue(i, "Supporter");
var giftVariable = contributionList.GetFieldValue(i, "Donation Amount");
var sum = 0;
var shares = 0;
var tsSettings = "<p tabstops=19550,Right,,;29600,Left,,;>";
var ts = "<t>";
var totalStr = "Total ";
var stockStr = " & Stock";
var totalFormatted = FormatNumber("$#,###.00", Math.max(0, StringToNumber(sum)));
// Match data from linked file to current Supporter
if (donor_id == idVariable) {
// Look at current record and see if it contains the word "Share(s)"
// or not and act accordingly
if (giftVariable.match(/(^|\W)share($|\W)/i) || giftVariable.match(/(^|\W)shares($|\W)/i)) {
// Turn switch "on" if donation amount is a share or shares so
// we can have the " & Stock" appended to our string.
shares = 1;
// Because this donation is/are shares, we must "zero" this
// amount to make the math work when we sum everything up...
giftVariable = 0;
// This is where we are keeping our running total...
sum += giftVariable[i];
} else {
// This record was not a donation of share(s) so we now have to
// determine whether we are dealing with postive or negative numbers
// and then strip out all of the non-number characters, remove and
// replace the () whis just a "-," leaving us with a number we can
// work with...
// If number has parenthesis, then deal with it...
if (giftVariable.indexOf("(")) {
// Strip out all the ()$, characters...
giftVariable = giftVariable.replace(/[()$,]/g,"")
// Append the minus sign to the number...
giftVariable = "-" + giftVariable;
sum += giftVariable[i];
} else {
giftVariable = giftVariable.replace(/[$,]/g,"");
sum += giftVariable[i];
}
}
}
}
// Return Total...
if (shares == 1) {
return tsSettings + totalStr + ts + totalFormatted + stockStr;
} else {
return tsSettings + totalStr + ts + totalFormatted;
}
Any assistance would be greatly appreciated!
The problem (and code) needs to be broken into smaller, atomic steps. From your description it sounds like you should:
load a text file into memory
for each line in the file
extract: {
donor_id
charity
gift
and store the results in a contributions dictionary
for each item in the contributions dictionary
transform gift string into {
dollarAmount: float with a default of 0.0
stock: name with a default of ""
}
create an empty dictionary called totals
each item will have the shape {
id
dollarAmount as a float
stocks an an array
}
for each item in the contributions dictionary
lookup the id in the totals dictionary
if it exists
totals[id].dolarAmount += item.dollarAmount
totals[id].stocks.push(item.stock)
otherwise
totals[id].dollarAmount = item.dollarAmount
totals[id].stocks = [item.stock]
normalize your charities
for each item in totals dictionary
remove any empty strings from item.charities
create your report
for each item in totals dictionary
write`${item.id} donated `${item.dollarAmont}` ${item.stocks.length > 1 ? 'and stock' : ''
I believe you are trying to do too many things at once. Instead, the goal should be to normalize your data before you attempt to perform any calculations or aggrgrations, then normalize your aggregrations before writing your summaries or reports.
I would also stay away from using any direct string manipulation. You should have a dedicated function whose only purpose is to take a string like "($20.34) and 1 share of APPL" and return either 20.34, -20.34, or 0.0. And a different function whose only purpose is to take the same string and return either true or false is stock was present.

How to get all the text separately from the bracket using javascript regular expression

I have a sentence stored in a variable.That sentence I need to extract into 4 parts depends on sentence which I have put into variables in my code,I can able to extract here and get into console but I am not getting the whole text of inside the bracket,only I am getting first words.Here is the code below.Can anyone please help me.
HTML
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul class="messages">
SCRIPT
$(document).ready(function() {
regex = /.+\(|\d. \w+/g;
maintext = "Welcome to project, are you a here(1. new user , 2. test user , 3. minor Accident or 4. Major Accident)";
matches = maintext.match(regex);
text_split0 = matches[0].slice(0, -1);
text_split1 = matches[1];
text_split2 = matches[2];
text_split3 = matches[3];
text_split4 = matches[4];
console.log(text_split0);
console.log(text_split1);
console.log(text_split2);
console.log(text_split3);
console.log(text_split4);
$(".messages").append('<li>'+text_split0+'</li><li>'+text_split1+'</li><li>'+text_split2+'</li><li>'+text_split3+'</li><li>'+text_split4+'</li>');
// $("li:contains('undefined')").remove()
});
function buildMessages(text) {
let messages = text.split(/\d\.\s/);
messages.shift();
messages.forEach((v)=>{
let msg = v.replace(/\,/,'').replace(/\sor\s/,'').trim();
$('.messages').append(`<li>${msg}</li>`);
// console.log(`<li>${msg}</li>`);
});
}
let sentenceToParse = "Welcome to project, are you a here(1. new user , 2. test user , 3. minor Accident or 4. Major Accident)";
buildMessages(sentenceToParse);
Use the split function on the String, keying on the digits (e.g. 1.), you will get the preface and each of the steps into an array.
Use the shift function on the Array removes the unneeded preface.
Use forEach to iterate over the values in the array, clean up the text.
Using replace to first remove commas, then remove or with spaces on either side.
Use trim to remove leading and training whitespace.
At this point, your array will have sanitized copy for use in your <li> elements.
If you're only concerned with working through a regex and not re-factoring, the easiest way may be to use an online regex tool where you provide a few different string samples. Look at https://www.regextester.com/
Ok, Try another approach, cause regex for this isn't the best way. Try this:
$(document).ready(function() {
// First part of sentence.
var mainText = "Welcome to project, are you a here(";
// Users array.
var USERS = ['new user', 'test user', 'minor Accident', 'Major Accident'];
var uSize = USERS.length;
// Construct string & user list dynamically.
for(var i = 0; i < uSize; i++) {
var li = $('<li/>').text(USERS[i]);
if(i === uSize - 1)
mainText += (i+1) + ". " + USERS[i] + ")";
else if(i === uSize - 2)
mainText += (i+1) + ". " + USERS[i] + " or ";
else
mainText += (i+1) + ". " + USERS[i] + " , ";
$(".messages").append(li);
}
console.log(mainText); // You will have you complete sentence.
}
Why that way is better? Simple, you can add or remove users inside the user array. String together with your user list will be updated automatically. I hope that help you.

Passing a string through an array looking for regEx

I'm currently making a chatbox in JQuery. I've been using indexOf but I think it might be more efficient to use regExp.
my current code is
function ai(message){
if (username.length<3){
username = message;
send_message("Nice, to meet you " + username + ", how are you doing?");
}
if(message.indexOf("how are you?")>=0) {
send_message("I'm feeling great!");
}
if(message.indexOf("weather")>=0 ){
send_message("In England it is shitty");
}
var n = message.search(/\b(cat|cats|kitten|feline)\b/i);
if (n !== -1) {
send_message("i hate cats");
}
else {
for (i=0; i <= botChat.length; i++) {
var re = new RegExp (botChat[i][0], 'i');
if (re.test(message)) {
var length = botChat[i].length - 1;
var index = Math.ceil( length * Math.random());
var reply = (botChat[i][index]);
send_message(reply);
}
}
}
}
and a typical line from my array is
new Array ("I need (.*)\." , "Why do you need $1?", "Would it really help you to get $1?" , "Are you sure you need $1?"),
i'm trying to demonstrate the ways of creating a chatbot. The first four responses work perfectly
it takes a name, comments on the weather and can search for cats. What it can't do is perform the loop. Has anyone any suggestions?

In Javascript, how do you access key value data from an object in a mixed array?

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.

Categories