Add integer value to function method [closed] - javascript

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I have a function I call with nameOfFunction(); the output of the function is an integer eg. 10.
I also have var number = 5;.
I cannot change the function nameOfFunction(); or substitute it with another variable.
Is there a way to add number to nameOfFunction(); so the output of nameOfFunction(); will equal 15?
Like this:
nameOfFunction() + number = nameOfFunction();
output would be
10 + 5 = 15
Edit with more info: NameOfFunction(); is the total cost of all items in the cart of my ecommerce site. It is the output of all the functions required to calculate the number of items and their amounts.
The number variable is the delivery charge that changes depending on the amount in the cart. The total is rendered using NameOfFunction(); and the value posted to a form.
I need to manipulate the output of NameOfFunction(); with altering the functions that define it. Adding number must occur after.
I cant show the code as it is obtuse and out of context would not make sense.

I cannot change the function nameOfFunction(); or substitute it with another variable.
From your subsequent comments, my guess (and the guess of a now-edited and -deleted answer — apologies to Ele, you got it right) is that you can, you just don't realize you can. In a normal scenario, this will do it (not the same as that deleted answer, stuck to ES3-level features):
var oldFunction = nameOfFunction;
nameOfFunction = function() {
return oldFunction.apply(this, arguments) + 5;
};
The identifier (technically, binding) of the function is writable by default, so the above remembers the old function, then replaces the value of its binding with a new function that calls the original and adds 5 to the result. The code uses Function#apply and arguments to ensure that both this and all arguments passed to the function are passed on by the wrapper.
Now, all calls to nameOfFunction will see the old function's return value with 5 added to it.
Live Example:
// The original function
function nameOfFunction(n) {
return n * 15 + 7;
}
// Us hijacking it:
var oldFunction = nameOfFunction;
nameOfFunction = function() {
return oldFunction.apply(this, arguments) + 5;
};
// All calls to it will now see the new return value:
console.log(nameOfFunction(2)); // 42

Store in a temporary variable whatever your nameOfFunction returns and add whatever value you want to add to that.
let nameOfFunction = function() {
return 10;
}
let temp= nameOfFunction();
let ans = temp+5;
console.log(nameOfFunction()+5);

Related

Generation of random numbers - Math.random() [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 14 days ago.
This post was edited and submitted for review 14 days ago.
Improve this question
I was working trying to generate a random number the other day. The assignment is basically that, given an array with names, I was gonna log names on the console at random. I tried to generate a random number that is gonna help accessing the names working as the index of the elements (e.g., array[random_number_as_index]).
My confusion started when storing the method Math.random() in a variable and accessing that same variable, the result was the exact same number over and over. My line of code looks something like this.
const randomNumber = Math.floor(Math.random()*10));
Whereas when part of a function, e.g.,
function randomNum () {return Math.floor(Math.random()*10));}
would actually generate a random number every time the function is invoked. My expectation was that, upon accessing the variable, a random number was gonna be generated every single time, which was not the case, and only works if it is within a function.
const randomNumber = Math.floor(Math.random()*10));
Generates a random number, then assigns that random number to randomNumber.
randomNumber is a constant variable (meaning its value cannot be changed after the fact).
You're generating one random number, then saving it in a variable.
function randomNum () {return Math.floor(Math.random()*10));}
Defines a function that returns a random number when called.
Each invocation of randomNum generates a new random number.

How to get the first value in JSON brackets [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I have a function that returns the following:
{ 'random_string': '' }
Where random_string is an id that I do not know until it is returned.
How do I extract the value of random_string in JS? Thank you.
var a = { 'random_string': '' }
console.log(Object.keys(a)[0])
Your variable a has a value of type Object. Take a look at the Object prototype's documentation and see which methods are available to you: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object
You're trying to get your object's first key, and so conveniently you can use Object.keys as follows:
var a = { 'random_string': '' }
// Get array of Object's key values as strings
var aKeys = Object.keys(a);
console.log(aKeys);
// Print first key, in this case you only have one
console.log(aKeys[0]);
But based on your comments, you're going about this wrong.
If your "random_string" property identifier is truly random, you'd want to store the random string as an object property value.
That might look something like this:
// Generate some random string value
var random = Math.random().toString(36).substring(7);
// Create an object with a predefined object property identifier
var data = { 'random_value': random };
// Access the random value using your known property identifier
console.log(data.random_value);

Why does my for loop return a value just once? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
function getValue () {
console.log(1);
return 2;
};
for (let i = 0; i < 1000; i++) {
getValue();
}
It will print 1 a thousand times, but here it will return just once that two at the end of loop. Why?
It's not being run once. Most likely what you're seeing is this:
See the "1000"? That means that "1" was output 1000 times. Your javascript console is simply trying to save you some space. If you change the number to something that's different every time you'll see unique instances of the message:
If your question is "why does it say '1' 1000 times but only '2' a single time" then the answer is very simple. You're only executing the function but never printing its return value, and therefore you'd see the last return value. If you want to print 2 as well, use console.log( getValue() );.
"Why would I ever want the result of the last call???"
Because stuff like this is awesome:
maybe I've got what you mean....
you see 1000's 1, than a 2, and you wonder why you only see one 2?
your function acctually returns 2 for 1000 times, but your code do nothing with it, it's "lost", and the console output your last usable return value, the 1000th 2 of the getValue function.
if you add a new return after the loop, you will not see the 2 and you will see this new return value, like this:
function getValue () {
console.log(1);
return 2;
};
for (let i = 0; i < 1000; i++) {
getValue();
};
var x=function(){
return "return value string, that you see only once in the console"}
x();
x();
as you can see, we call the x() function twice, but we see the returned string only once in the console.

How do I make it show up how many questions the user gets right? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I am trying to make a simple Algebra quiz in HTML and JavaScript, but can't figure out how to make it show up how many answers you got correct. I made it to where the it would turn the correct answer variables into booleans, true is correct and false is incorrect. Then I made if and else statements to see how many answers were correct but the alert (which will be changed) is just displaying zero no matter what. Here is a link to my code.
https://jsbin.com/yivapi/edit?,js
Trenner, I'm not going to be able to answer your question properly without untangling your code, so what I thought I'd do is show you a different (and hopefully easier) way to approach the problem. I hope that's okay.
HTML
Here are the inputs for the questions as I imagine you've set them out. I've only used three here for simplicity. There's a submit button which I'll get to in a moment.
<input id="q1" />
<input id="q2" />
<input id="q3" />
<button id="submit">Submit</button>
JavaScript
First we grab our submit button and assign a function getAnswers to its click event.
var submit = document.getElementById('submit');
submit.onclick = getAnswers;
This is a shortcut function to grab the input values so you don't need to keep writing document.getElementById(id).value later.
function getValue(id) {
return document.getElementById(id).value;
}
OK. So now, instead of having a load of if...else statements we're going to use an object to store all of our information. If you've used other languages they might call something like this a hash map. Basically it's a store of information that has key/value pairs and it's great for storing connected information together. In this case each question is a key which has another object as its value, and that object's keys are value and answer, and it's values are the value of the input element and the actual answer.
function getAnswers() {
// create the object
var quiz = {};
// for each question assign set up a new key (question1)
// and get the input value using our shortcut function.
// We set the actual answer here too.
quiz.question1 = { value: getValue('q1'), answer: '2√19' }
quiz.question2 = { value: getValue('q2'), answer: '√87' }
quiz.question3 = { value: getValue('q3'), answer: '8x√2' }
// Once we've loaded the questions, we can check the answers
// We pass in our quiz object as an argument
checkAnswers(quiz);
}
Here we use a loop to iterate over our quiz object. A simple loop of 7 lines instead of all those horrible if...else statements.
function checkAnswers(quiz) {
// set up out correctAnswers variable
var correctAnswers = 0;
// loop over the quiz object and...
for (var q in quiz) {
// ...for each question we test the input value we've stored
// against the answer also held in that object
// If they match increase the correctAnswers variable
if (quiz[q].value === quiz[q].answer) {
correctAnswers++;
}
}
// finally alert the correctAnswers
alert("You got " + correctAnswers + " out of 15 questions right!");
}
This DEMO will show you the working code. Just add 2√19 into the first input box and press submit and you will get an alert of 1 correct answer(s).
Sorry for not directly answering your question, but I hope you find this code interesting and useful. Good luck with your JavaScript coding.

Get a list of games and their properties from JSON [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I'm trying to access a list of Casino Games and their properties from a JSON object in order to get them to display on the website. This is where I am so far.
var x = $.getJSON("http://api.bosurl.net/V1/Progressive.asmx/GetProgressiveGames?format=json&callback=?", ProcessProgressiveGames);
console.log(x);
function ProcessProgressiveGames(progressiveGames) {
console.log(progressiveGames.d.Games[0].GameName);
}
What's there best way to do this. If you check your console, you'll see that var x contains the object with the game data.
See also: http://pasteboard.co/kXb1Voq.png
Related fiddle: http://jsfiddle.net/emporio/vz24dtm8/5/
This question is unique because it requires accessing unique properties. The answers also provide a multitude of ways to retrieve the data.
DEMO
JS
var Games;
var x = $.getJSON("http://api.bosurl.net/V1/Progressive.asmx/GetProgressiveGames?format=json&callback=?", function (data) {
Games = data.d;
}).done(function () {
document.getElementById('choice').innerHTML=ProcessProgressiveGames(Games);
});
function ProcessProgressiveGames(progressiveGames) {
return progressiveGames.Games[0].GameName;
}
$.getJSON function returns promise and the proper way to handle data returned from this address is to set second argument - function to handle data
$.getJSON("http://api.bosurl.net/V1/Progressive.asmx/GetProgressiveGames?format=json&callback=?", ProcessProgressiveGames);
function ProcessProgressiveGames(progressiveGames) {
// Note that progressiveGames has a property 'd' containing the data we're interested in.
console.log(progressiveGames);
document.getElementById('choice').innerHTML = ProcessProgressiveGames(x);
return progressiveGames.d.Games[0].GameName;
}
http://jsfiddle.net/vz24dtm8/7/
You can try like this
var x = $.getJSON("http://api.bosurl.net/V1/Progressive.asmx/GetProgressiveGames?format=json&callback=?", ProcessProgressiveGames);
http://jsfiddle.net/vz24dtm8/8/
function ProcessProgressiveGames(data) {
// Note that progressiveGames has a property 'd' containing the data we're interested in.
return document.getElementById('choice').innerHTML=data.d.Games[0].GameName;
}
<pre>Use callback function to get the json value and pass the parameter in callback function</pre>
http://jsfiddle.net/rajen_ranjith/vz24dtm8/13/

Categories

Resources