Sorry for being vague and confusing everyone, Im grateful for all the feedback but let me explain what i am trying to do.
I want to create an object called Multiplier with two methods: multiply and getCurrentValue
multiply should initially return the number supplied * 1 and from then on whatever the
current value is times the number supplied, getCurrentValue should return the last
answer returned from multiply.
Hey everyone I am having a little trouble grasping this concept.
Here is my code so far:
var multiplier = {
function multiply(){
alert("Input a number to be multiplied by 1")
var a = prompt("Input your desired number");
var b = a * 1;
return alert(b);
}
}
multiply();
any help or further explaining on how i would go about this would be appreciated
var multiplier = {
lastValue: null,
getCurrentValue: function() {
return lastValue;
},
multiply: function() {
alert("Input a number to be multiplied by 1")
var a = prompt("Input your desired number");
var b = a * 1;
lastValue = b;
return alert(b);
}
}
This should do what you want. You're defining an object named multiplier, that has two functions and a variable to save the last value.
Of course, there are other ways to accomplish this, but your question is a little vague.
A more object oriented approach would be like so.
function Multiplier() {
var lastValue = null;
this.getCurrentValue = function() {
return lastValue;
};
this.multiply = function() {
alert("Input a number to be multiplied by 1");
var a = prompt("Input your desired number");
var b = a * 1;
lastValue = b;
return alert(b);
}
}
With this approach, your lastValue variable is private. You've only exposed the two functions. Now you can create a new one of these objects whenever you need one, like so.
var myMultiplier = new Multiplier();
And you can call functions on that multiplier like so.
myMultiplier.multiply();
Related
I'm trying to solve the problem. When the user enter two numbers via ** prompt **, after the display shows the final result. Simple constructor, but this code only accepts the first value, I cannot force it to take the second one too, in order for sum both values
function Num (firstNum) {
this.firstNum = firstNum;
this.read = function() {
this.value = this.x + this.firstNum; {
return this.x = +prompt('a');
}
};
}
let num = new Num(10);
num.read();
num.read();
alert(num.value);
As other commenters have suggested you should probably edit your question to make it clearer. But if I had to take a guess here's my answer:
Lookup "curry functions" or "partial application". You can basically use closures to stash the value from the first prompt until you receive the value from the second.
const sumTwo = firstNum => secondNum => firstNum + secondNum;
// then when you want to use it;
const plusTen = sumTwo(prompt(10);
const resultA = plusTen(prompt(2)); // this will be 12
const resultB = plusTen(prompt(5)); // this will be 15
solve
function Num (firstNum) {
this.value = firstNum;
this.read = function() {
this.value += +prompt('a?', 0);
};
}
let num = new Num(10);
num.read();
num.read();
alert(num.value);
I have a Node project where I create a Unit and an AddGate:
var Unit = function(value, weight) {
this.value = value;
this.weight = weight;
}
var AddGate = function() {
this.sum_function = function(units) {
sum = 0;
for (unit in units)
sum += unit.value;
return sum;
};
};
AddGate.prototype = {
forward: function(units) {
this.units = units;
this.output_unit = new Unit(this.sum_function(units), 0.0);
return this.output_unit;
}
}
I create some Units, an AddGate, and a ForwardNeuron (guess what I'm making):
var in_1 = new Unit(1.0, 0.0);
...
var in_9 = new Unit(3.0, 0.0);
var add = new AddGate();
var forwardNeuron = function() {
a = add.forward({in_1, in_2, in_3, in_4, in_5, in_6, in_7, in_8, in_9});
};
forwardNeuron();
But for some reason, when in sum_function of AddGate, I can access each unit of units fine, but when I try to access unit.value, it says it's undefined, even though I've clearly initialised it. Am I missing something?
As the comments specify, for (let unit in units) will actually set unit as the key of the units object. You can correct this in a few ways such as using units[unit].value, but it would make more sense to me for the arguments to forward and sum_function to be an array. More or less as simple as:
add.forward([in_1, in_2, in_3, in_4, in_5, in_6, in_7, in_8, in_9]);
The sum would be a reduce operation on the array as in:
return units.reduce((sum, unit) => sum + unit.value, 0);
FYI 4castle's response worked for me - I wrote:
sum += units[unit].value;
That did the trick for me. Thanks again to 4castle and trincot for their speedy responses.
EDIT: The above is even better.
I have a equation like this stored in a varible
(50 * 1.07^1) its very simple. I want to know how I can change the power each time a function runs like so: 50*1.07^2, 50*1.07^3 and so forth. Any help?
Here is my code:
var mathForCost = 50 * 1.07 ^ 1;
function gainCoinsPS() {
if (coins >= costPS) {
coinsPS += 10;
coins -= costPS;
// Here is where I am changing the cost each time the function runs,
// so I need to make the power(^1) add 1 each time
costPS = document.getElementById("changePrice1").innerHTML = "Cost: " + costPS;
} else {;
alert("You dont have enough coins!");
};
}
Save the power to a variable, and you can update it when needed. It is preferred that you put the equation into a function and pass power to it, and return the solution.
var power = 1,
eq = function(p){
return 50*1.07^+p; // returns solution
};
for(var i=0; i<10; i++){
power = i;
console.log( eq(power) ); // solution
}
You can store your power in a variable and increment it each time your function is called.
var power = 1;
function calculate() {
console.log(50 * Math.pow(1.07, power));
power++;
}
calculate();
calculate();
calculate();
In Javascript you can't really store an equation in a variable, except maybe as a string (but that is fraught with issues of its own). Your function will be evaluated the moment you execute, and the value of the output will instead be stored in the variable.
To do what you want to do, you would be better having a function that runs the equation, and increments the power each time-- this works if the power is in a higher scope (or it can be accomplished with a closure)
var power = 1;
function getCost()
var cost = Math.pow(50*1.07, power);
power++;
return cost;
}
Each time this function runs, it returns the calculated cost and also increments the value of power, so it will be one higher the next time it runs.
Alternately, if you wanted to go the closure route, you could do something like this:
var getCost = (function () {
var power = 1;
return function () {
var cost = Math.pow(50*1.07, power);
console.log(power);
power++;
return cost;
}
})();
You can store a state to the function that runs the equation. This helps you avoid adding more state outside of the function. Let the function keep track of how many times it has been called.
function calc() {
if (!this.i) {
this.i = 1;
}
return (50 * Math.pow(1.07, this.i++));
}
console.log(calc());
console.log(calc());
console.log(calc());
There is Math.pow function is javascript for this.
You can use something like this
var pow = 1;
for(var power=1; power<limit; power++){ // run the loop upto a limit
console.log(Math.pow(50*1.07, power);
}
To increment power of 1.07 by 1, just multiply value by 1.07 every time (pow function is not needed at all)
var mathForCost = 50 * 1.07;
...
mathForCost = mathForCost * 1.07;
You could use a function for it.
getCost = function (n) { return 50 * Math.pow(1.07, n); };
Or with ES6's arrow function
getCost = n => 50 * Math.pow(1.07, n);
Call it with
value = getCost(1);
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
Here I have two "classes" made Cards and card. Cards is essentially an array with specific methods:
add card
remove card
sort and shuffle
Card is an object used for holding a suit a value and outputting a string concatenating both.
My problem here is trying to run this code, namely setup() on a button click.
I find that when I just create a card, it still runs. I know this because the output still changes to hello world.
But when I try to add a card to the cards class, or deck. the script stops running. I don't know why this is, I have a feeling that it doesn't like how I used an Array.
Thats question one.
My second question is that when I
var temp= new card('c','2');
alert(temp.getvalue());
This also fails.
Any insight as to what I did wrong here would help and be appreciated.
function setup() {
var temp = new card('c', '2');
var textbox = document.getElementById("output");
textbox.value = "Hello, world!";
};
Array.prototype.shuffle = function () {
for (var i = this.length - 1; i > 0; i--) {
var j = Math.floor(Math.random() * (i + 1));
var tmp = this[i];
this[i] = this[j];
this[j] = tmp;
}
return this;
}
function card(s, v) {
this.suit = s;
this.value = v;
this.getvalue = function () {
return (suit.toString() + value.toString());
};
this.getSortOrder = function () {
var factor;
if (this.suit == 'c') {
factor = 0;
}
else if (this.suit == 'd') {
factor = 1;
}
else if (this.suit == 'h') {
factor = 2;
}
else if (this.suit == 's') {
factor = 3;
}
else {
factor = -2;
}
return (this.value + 13 * factor);
};
};
function Cards() {
this.list = new Array();
this.Addcard = function (c) {
list.push(c);
};
this.removeCard = function (c) {
list.splice(list.indexOf(c), 1);
};
this.lookat = function (i) {
return list[i];
};
this.sort = function () {
list.sort();
};
this.shuffle = function () {
list.shuffle();
};
this.prototype;
};
Here's one thing:
this.getvalue = function () {
return (suit.toString() + value.toString());
};
You need to access suit and value with this:
this.getvalue = function () {
return (this.suit.toString() + this.value.toString());
};
Edit:
There's a lot more like that in your code (see Cards function). Javascript does not automagically place "this" there for you like other language, because it doesn't have classes, it has prototypes.
Whenever you try to access a "member variable", give it some context, use this.
Other code style tips:
use [] instead of new Array()
comment large blocks of code with /* and */
constructors should be capitalized (Card, not card) and functions should be camel case (addCard, not Addcard)
I am trying to make a script to pick random number between two numbers . but it picks same number sometimes. i donot want to repeat same number until array is finished .
Here is my code
$(document).ready(function () {
abc();
test = array();
function abc() {
res = randomXToY(1, 10, 0);
$('#img' + res).fadeTo(1200, 1);
//$(this).addClass('activeImg');
//});
setTimeout(function () {
removeClassImg(res)
}, 3000);
}
function removeClassImg(res) {
$('#img' + res).fadeTo(1200, 0.1);
//$('#img' + res).removeClass('activeImg');
abc();
}
function randomXToY(minVal, maxVal, floatVal) {
var randVal = minVal + (Math.random() * (maxVal - minVal));
return typeof floatVal == 'undefined' ? Math.round(randVal) : randVal.toFixed(floatVal);
}
});
Does Anybody have idea about this ...
You'll have to maintain a list of numbers that have already been generated, and check against this list. Re-generate a new number if you find a dupe.
If you do not want the random numbers repeating themselves you have to keep track of the some way.
If you have the range you are dealing with is relatively small, you can create an array with all possible results and simply randomly pick out of it.
function Randomizer(minVal, maxVal, floatVal){
var possible_results = []; // for larger arrays you can build this using a loop of course
var randomization_array = [];
var count = minVal;
var incrementor = floatVal || 1; // set the distance between possible values (if floatVal equals 0 we round to 1)
while (count <= maxVal) {
possible_results.push(count);
count += incrementor;
}
this.run = function(){
// if randomization_array is empty set posssible results into it
randomization_array = randomization_array.length ? randomization_array : $.merge(randomization_array, possible_results);
// pick a random element within the array
var rand = Math.floor(Math.random()*randomization_array.length);
// return the relevant element
return randomization_array.splice(rand,1)[0];
}
}
and in order to use it (it creates a specialized object for each possible range):
rand = new Randomizer(1,10,0);
rand.run();
note that this approach does not work well for very large ranges