using value from previous object property function - javascript

Cannot use value from previous object property function starting(); when trying to combine in output below; getting NaN for timeTaken(); function. Presumably starting isn't reporting within that function, any suggestions?
starting : function() {
return this.slow * this.driveTime + " mph ";
},
timeTaken : function() {
return this.starting / this.driveTime + " seconds ";
},
document.getElementById("car").innerHTML = car.starting() + car.timeTaken();
Should I rather try to nest both functions in same one function? I'm open to more optimal methods.
Full object code:
var car = {
cruise: "35",
slow: "5",
stop: "0",
driveTime: "4",
starting : function() {
return this.slow * this.driveTime + " mph ";
},
timeTaken : function() {
return this.starting / this.driveTime + " seconds ";
},
};

That's because this.starting is a function. Basically what you are asking JavaScript to do is "take the starting function and divide it by this.driveTime". This is undefined.
What I'm guessing you want is something like this:
var car = {
cruise: 35,
slow: 5,
stop: 0,
driveTime: 4,
starting: function() {
return this.slow * this.driveTime;
},
timeTaken: function() {
return this.starting() / this.driveTime;
},
toString: function() {
return this.starting() + " mph " + this.timeTaken() + " seconds ";
}
};
console.log(car.toString());
console.log(car.starting());
console.log(car.timeTaken());
Note that I changed starting() and timeTaken() to just return numbers (rather than "x mph" or "x seconds"). This allows you to do math on the results from those functions.
I added the toString() function to make it easier to get a string representation of the data that I'm assuming you wanted to print out.
EDIT: As noted by Peter Behr's answer, you should store cruise, slow stop, and driveTime as numbers rather than strings. I have updated my example to show this.
Further Reading
JavaScript data types and data structures at MDN

Additionally, you're doing math on strings, which isn't a great idea. Make the object properties numbers to begin with.

starting method return a String so divide a string by a number will result as NaN

Related

how to perform aggregation and expression from given string (formula)?

I want to do aggregation operation by identifying "sum(a)" as in the below string and need to perform some logical operation to get sum, avg, count or percentage(i have separate method to do that so don't worry about that).
expression like below,
= '"sum(a)" * 10 + "count(b)"'
Here a and b is key word. Based on the key word i will perform the operation. But i need to identify operation name and key word in the above string.
Then, I need to execute the expression without using eval function for following expression. like below,
"10 * 10 + 22"
Note: I am trying to use Function constructor, but i am facing performance issue.(Use string to call function without eval())
You can use Array.proptotype.reduce:
const values = [2,3,4];
const sum = values.reduce((sum, current) => sum + current, 0);
console.log(sum * 10 + values.length);
function sum(values){
return values.reduce(function(s, n){
return s + n;
}, 0)
}
function count(values){
return values.length
}
alert( sum([2,3,4]) * 10 + count([2,3,4]) )

Advancing numeric string in localstorage

Working on a little task tracker applet that uses localstorage to both store tasks and keep a running tab of how many tasks have been created to date. The later is my issue.
Here's what I'm running, the issue is contained to variables "taskTracker" and "advanceTask".
function saveTask() {
var task = $("#task").val();
var taskDate = $("#taskDate").val();
if (newUser == null) {
var taskNumber = 0;
localStorage.setItem("taskTracker", "0");
localStorage.setItem("newUser", "no");
}
else {
var taskNumber = localStorage.getItem("taskTracker");
}
var advanceTask = taskNumber + 1;
localStorage.setItem('task' + taskNumber, task);
localStorage.setItem('task' + taskNumber + 'date', taskDate);
localStorage.setItem("taskTracker", advanceTask);
console.log(advanceTask);
displayTasks();
}
If you take a look at the "advanceTask" variable, my intention is to advance the numerical value stored in "taskTracker" each time this function is invoked. However, all I'm getting is an additional "1" appended to the value each time.
Thoughts? <3
There is a difference between string + number and number + number. Your current solution is like the stringPlusOne function below. You need to convert the string to a number (using parseInt is one way) and then do the math, like the stringPlusOne2 function below
function stringPlusOne(str) {
console.log(str + 1);
}
function stringPlusOne2(str) {
console.log(parseInt(str, 10) + 1);
}
stringPlusOne("2");
stringPlusOne2("2");

Why would we declare a 2nd variable in the below code?

Why would we declare a second variable (val) when we can use the parameter of the function as a variable?
Here's how it looks like on codecademy:
var divideByThree = function (number) {
var val = number / 3;
console.log(val);
};
divideByThree(6);
I've made some changes as below:
var divideByThree = function (number) {
number = number / 3;
console.log(number);
};
divideByThree(6);
And it works pretty fine!!
In your example, you do not need to preserve the original value of the parameter. However, you may find it easier to use extra variables in the future for more complicated functions.
Here is an example:
// This function uses the parameter "rawNumber" as a variable, but also uses an extra variable "number"
function TestThis(rawNumber, p) {
// Convert the input (string) to integer
// parseInt returns NaN or integer. Truncates decimals
var number = parseInt(rawNumber);
// Check to see if the result is NaN or is an integer
if (isNaN(number)) {
Log(rawNumber + " is not a number.", p); // Log is my imitation of console.log()
}
// will run if number is type int
else {
if (number > 0 && number <= 100) {
Log(rawNumber + " is a valid number.", p);
} else {
Log(rawNumber + " is not between 1 and 100.", p);
}
}
}
You can see this code working in this Fiddle.
In this function I used an extra variable called "number" in three different places. I didn't have to, but it was easier than typing isNaN(parseInt(rawNumber)) and if(parseInt(rawNumber) > 0 && parseInt(rawNumber) <= 100). Codecademy was probably decided to teach you this way because it is easier to realize you can simplify your code than to realize you can simplify a more complex code through the use of extra variables.
Also, JK Price's answer brings up a readability issue. Simply put, this code is easier to read and understand:
function Example(number) {
var processedNumber = 5/(Math.log(1/number*3.14 - 7));
console.log("Message: " + (processedNumber * 2));
console.log("Message: " + (processedNumber / 10));
}
This code might be a little harder:
function Example(number) {
console.log("Message: " + ((5/(Math.log(1/number*3.14 - 7)) * 2));
console.log("Message: " + ((5/(Math.log(1/number*3.14 - 7)) / 10));
}
Variables are supposed to help the programmer write better and describe a better story. You can't have the same actor play multiple characters! One thing it does is to help keep variables separate.
The variable val in this case helps abstract the logic and most importantly help in debugging. If this was a long script and you saw that number was not what you originally passed it, you might consider it to be an error.

"Try...Catch" Block not Working with parseInt()

What I'm trying to do:
I have a javascript program that, when a button is clicked, takes in 4 strings from 4 text boxes in a form, and outputs those strings into a formatted textarea.
function testResults(form){
var errorhandle1 = parseInt(document.myForm.Item_Code.value);
var errorhandle2 = parseInt(document.myForm.Item_Cost.value);
var errorhandle3 = parseInt(document.myForm.Quantity.value);
//above variables are for error handling.
var d = " ";
var subtotal = parseInt(form.Item_Cost.value) * parseInt(form.Quantity.value);
var subtotalValue = parseInt(document.myForm.Subtotal.value);
var testVar = "Item Code: " + form.Item_Code.value + d +
"Item Name: " + form.Item_Name.value + d +
"Item Cost: " + form.Item_Cost.value + d +
"Quantity: " + form.Quantity.value + '\n';
document.myForm.myTextarea.value += testVar;
document.myForm.Subtotal.value = parseInt(subtotal) + subtotalValue;
document.myForm.Sales_Tax.value = document.myForm.Subtotal.value * salestax;
document.myForm.Total.value = parseInt(document.myForm.Subtotal.value) + parseFloat(document.myForm.Sales_Tax.value);
}
The above code works just fine, and does exactly what I want it to do for the scope of my program.
try {
if ((isNaN(errorhandle3) == true) || (isNaN(errorhandle2) == true)) {
throw "Error1";
}
} catch (e) {
if (e == "Error1") {
alert("Error! You must enter a number into the qty and cost fields!");
}
}
What I'm trying to accomplish with the try...catch block is simply to make sure that
document.myForm.Item_Code.value
document.myForm.Item_Cost.value
document.myForm.Quantity.value
are actually numbers.
The try...catch statements trigger every time I run the program and doesn't care what I put in the corresponding text boxes. I would greatly appreciate any and all insight on this!
Also: I looked at both of these links and was unable to understand my problem.
javascript parseInt return NaN for empty string
http://www.w3schools.com/jsref/jsref_isnan.asp
Your root problem here is that isNaN() tests to see if the value is NaN. It does not test to see if a string is a proper number. It has some coercion rules to try to deal with strings, but that really isn't what it is designed for.
You can see ways to test if something can be parsed into a valid number here: Validate decimal numbers in JavaScript - IsNumeric()
It's worth reading the detail in the good answers there, but it boils down to something like this which is a bit more than you need, but is general purpose:
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
And, then there's no reason to use exceptions in your code, so you can just do this:
if (!isNumber(errorhandle3) || !(isNumber(errorhandle2)) {
alert("Error! You must enter a number into the qty and cost fields!");
}
Also, in your code, some .Value properties look like maybe they should be .value (lowercase).
In your first code block
var errorhandle2 = parseInt(document.myForm.Item_Cost.Value);
var errorhandle3 = parseInt(document.myForm.Quantity.Value);
You are using Value, which should be value, that's case-sensitive.
By the way, isNaN returns boolean, you don't have to compare with true

Javascript : function checking if the answer to score as a percentage has more than 2 decimal places

I want to create a dynamic worksheet for my students, so every time they do it they see different questions. The question that I am trying to create ie, calculate the percentage if I scored X out of a total of Y.
Here are the 3 functions which work together, the first generates some numbers, calls the second, which in turn calls the third to check if it more than 2 decimal places, then if it is, the second creates a new SCORE number which repeats until it finds an answer which is 2 decimal places or less, then returns the SCORE number which works to the first, which outputs it.
I keep getting one of three outputs : undefined where the SCORE should be, no output at all, or a working question.
I cannot understand how it works sometimes, throws undefined sometimes and gives completely nothing at other times.
Any ideas.
function scorePercent()
{
var output="";
var total = Math.floor((Math.random()*99)+1);
var score = Math.floor((Math.random()*(total-1))+1);
output = output + "<div>A score of " + chkScore(score,total) + " out of " + total + ".</div></br>";
document.getElementById("qOut").innerHTML=output;
}
function chkScore(n1,n2)
{
var answ = (n1/n2)*100;
if(dps(answ)>2)
{
var scoreNew = Math.floor((Math.random()*(n2-1))+1);
chkScore(scoreNew, n2);
}
else
{
return n1;
}
}
function dps(num)
{
var match = (''+num).match(/(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/);
if (!match) { return 0; }
return Math.max(
0,
// Number of digits right of decimal point.
(match[1] ? match[1].length : 0)
// Adjust for scientific notation.
- (match[2] ? +match[2] : 0));
}
You have a recursive function in your chkScore, but you're not return-ing the results from the "deeper" iterations.
Try this:
function chkScore(n1,n2){
var answ = (n1/n2)*100;
if(dps(answ)>2) {
var scoreNew = Math.floor((Math.random()*(n2-1))+1);
return chkScore(scoreNew, n2); // <-- return that.
} else {
return n1;
}
}
The missing return there, resulted in the function sometimes not returning anything.
The "deeper" iterations will return their value only 1 "level" up, so that "level" will have to pass it through, if you know what I mean.

Categories

Resources