How to take plus sign in variable - javascript

I want to calculate two numbers and its pretty simple.
But Is there any way to take operator in variable and then do the calculation?
var x = 5;
var y = 5;
var p = '+';
var z = x + p + y;
$(".button").click(function() {
alert(z);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="button">Click ME !</div>

Avoid eval whenever possible. For this example, a simple switch...case statement will be sufficient:
var x = 5;
var y = 5;
var z;
var p = "+";
switch (p) {
case "+":
z = x + y;
break;
case "-":
z = x - y;
break;
}
You can also use a map of functions:
var fnlist = {
"+": function(a, b) { return a + b; },
"-": function(a, b) { return a - b; }
}
var x = 5;
var y = 5;
var p = "+";
var z = fnlist[p](x, y);

Or use parseInt on the string which you will be adding the variable to:
var x = 5;
var y = 5;
var p = '-';
var z = x + parseInt(p + y);
$(".button").click(function(){
alert(z);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="button">Click ME !</div>

You are looking for eval function:
var x = 5;
var y = 5;
var p = '+';
var z = x + p + y;
$(".button").click(function(){
alert(eval(z));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="button">Click ME !</div>
However, you have to remember that using eval function is potentially risky. For example, if used in the wrong way it can allow one to make injection attacks. Debugging can be also more difficult. I suggest to read this question.

you can use the eval function:
var x = 5;
var y = 5;
var p = '+';
var z = eval(x + p + y);
alert(z);

Related

How can you add two random variables (with different values) together in Javascript?

This is my code as shown below. My first set is Fibonacci numbers, the second is Lucas Numbers
var f1 = 1;
var f2 = 1;
var f3 = 2;
var f4 = 3;
var f5 = 5;
var f6 = 8;
var f7 = 13;
var f8 = 21;
var f9 = 34;
var f10 = 55;
var f11 = 89;
var f12 = 144;
var l1 = 1;
var l2 = 3;
var l3 = 4;
var l4 = 7;
var l5 = 11;
var l6 = 18;
var l7 = 29;
var l8 = 47;
var l9 = 76;
var l10 = 123;
var l11 = 199;
var l12 = 322;
var num;
var num2;
I have it so that if num = 1, then you add fibonacci, if num = 2, then you add the lucas numbers.
function question(){
num = Math.floor(Math.random() * 2) + 1;
num2 = Math.floor(Math.random() * 2) + 1;
if(num = 1){
document.getElementById("question").innerHTML = "Find the two numbers in the Fibonacci Series which when added together make" + _______ // What goes here?
}
if(num = 2){
document.getElementById("question").innerHTML = "Find the two numbers in the Lucas Series which when added together make" + _______ // What goes here?
}
}
In the blank area, what goes there? I want to put the sum of 2 random variables (as shown above).
To start off, create two arrays holding the numbers as follows :
let fibNums = [1,1,2,3,5,8,13,21,34,55,89,144];
let lucasNums = [1,3,4,7,11,18,29,47,76,123,199,322];
As the next step create a function which can return the sum of two random numbers based on the array
function generateSum(arr, x, y){
console.log(arr[x], arr[y]); // the selected values from the array
return arr[x] + arr[y];
}
Now just call the function with the array name and by generating random index
generateSum(arrayName , Math.floor(Math.random()*arrayName.length), Math.floor(Math.random()*arrayName.length))
Based on your use case
if(num = 1){
generateSum(fibNums , Math.floor(Math.random()*fibNums.length), Math.floor(Math.random()*fibNums.length))
}
if(num = 2){
generateSum(lucasNums , Math.floor(Math.random()*lucasNums.length), Math.floor(Math.random()*lucasNums.length))
}

What's the best way to allocate the variables with multiple combinations

I want to reduce the initialization of multiple combination variables.
My aim is to create a function and pass a function with variable.
If I pass a variable x into function value(x); I should get output as "123". Similarly, if I pass a variable xy into function value(xy), then I should get output as "123456". Basically, I want to concatenate variables
Here is the javascript code as
var x = "123";
var y = "456";
var z = "789";
var a = "0-+";
var xy = x + y;
var yz = y + z;
var zx = z + x;
var xa = x + a;
var ya = y + a;
var za = z + a;
var ax = a + x;
var ay = a + y;
var az = a + z;
var xz = x + z;
var yx = y + x;
var zx = z + x;
var zy = z + y;
var xyz = x + y + z;
var xyza = x + y + z + a;
function value(input) {
console.log(input);
}
Sample execution as follows:
value(x); //output: 123
value(y); //output: 456
value(xy); //output: 123456
value(za); //output: 7890-+
In this case, there are lots of combination for the above variables i have defined to meet all possible combinations. I want to validate the user input from the above combination and also i dont want to write so many variables. Is there any possible easy solution ?
Please suggest. Thanks
I would declare a global object to store the variables as keys:
var globals = {
"x": "123",
"y": "456",
"z": "789"
};
Note that you can refer to your "variables" by globals.x, or globals.y (you can replace globals with a shorter keywork to reduce code of course).
It is a little extra effort to define the "variable names" with quotes.
However, now you get to use:
alert(Combinate("xz"));
// output: 123789
With a function like:
function Combinate(phrase) {
result = "";
for (var i = 0, len = phrase.length; i < len; i++) {
result += globals[phrase[i]];
}
return result;
}
Here's a JSFiddle.
You'll want to use some form of iterating over an array or object. As an example:
var x = "dave";
var y = "bill";
var z = "john";
var a = "suzan";
var people = [x,y,z,a];
for(i=0; i<people.length; i++) {
for(x=0; x<people.length; x++) {
value(people[i] + people[x]);
for(y=0; y<people.length; y++) {
value(people[i] + people[x] + people[y]);
for(z=0; z<people.length; z++) {
value(people[i] + people[x] + people[y] + people[z]);
}
}
}
}
// not sure why you'd have a function to wrap console.log(), but...
function value(input) {
console.log(input);
}
See in action on jsFiddle.
There are more elegant paths, but this should get you on the road to learning about JavaScript.

javascript scope : retain global variable value after a function

When the 'hypotenuse' function is called the value of 'x' changes from 1. Fix it so that 'x' is still 1 in the gobal scope.
var x = 1;
var y = 1;
function hypotenuse(a , b) {
var cSquared = a * a + b * b;
x = Math.sqrt(cSquared);
return x;
}
hypotenuse(x, y);
All you need to do to make this happen is redeclare the x variable using var within the function. This is will declare the x variable within the scope of the function, leaving the original, globally scoped x variable untouched:
var x = 1;
var y = 1;
function hypotenuse(a , b) {
var cSquared = a * a + b * b,
x = Math.sqrt(cSquared);
return x;
}
hypotenuse(x, y);
Or, using the code style which you originally adopted (splitting out var declarations):
var x = 1;
var y = 1;
function hypotenuse(a , b) {
var cSquared = a * a + b * b;
var x = Math.sqrt(cSquared);
return x;
}
hypotenuse(x, y);
For more detailed info on what is happening here, read up on javascript scope
Try this:
var x = 1;
var y = 1;
function hypotenuse(a, b) {
var cSquared = a * a + b * b;
var x = Math.sqrt(cSquared);
return x;
}
//console.log(hypotenuse(x, y));
//console.log('x = ' + x);

Javascript addition query

Don't feel foolishness in my question. Below is my scenario. Please advice
var num = 02;
var add = num + 1 ;
Getting result is 3, but I need it as 03. Is it possible.
You'll need to write a padding function:
function strpad(string, length, padChar)
{
var o = string.toString();
if(!padChar)
{
padChar = '0';
}
while (o.length < length)
{
o = padChar + o;
}
return o;
};
And then call it using:
var num = 3;
var add = strpad((3 + 1), 2); // will return '04' as a string.
you can do it like this
<script>
var num=2;
var add= parseInt(num + 2);
if(parseInt(add) <10)
{
add= '0'+add; // if single digit no. then concat 0 before the no.
}
</script>

javascript variable concatenation in loop

How am I supposed to concatenate this?
here's my javascript code
var c0 = document.all.ntext.value;
var c1 = document.all.stext.value;
var x;
for(x=0; x<2; x++)
{
a.innerHTML = c //contatenation needed
}
var c0 = document.all.ntext.value;
var c1 = document.all.stext.value;
var x;
for(x=0; x<2; x++)
{
a.innerHTML = c0 + с1
}
Is that what you want?
It'll be much better if you'll go this way:
var c = [document.all.ntext.value, document.all.stext.value];
var x;
for(x=0; x<c.length; x++)
{
a.innerHTML += c[0];
}
var needed = ['ntext', 'stext'];
a.innerHTML = needed.map(function(key) {
return document.all[key].value;
}).join('');
.map need a shim for old browsers.

Categories

Resources