I am writing JavaScript code that has a loop. There is statement in the loop:
foo = foo +1. ;
I want the code to treat foo as different variable each time the loop runs. For example:
first loop --> env.x = env.x + 2.0 ;
second loop --> env.y = env.y+ 2.0 ;
third loop --> env.z = env.z + 2.0 ;
I have looked at other solutions posted like using eval() and window() functions but still can't figure how to do this.
UPDATE: To help better understand my problem I am posting a part of the code:
if (profile.xChaos.toFixed(0) > 500.) {
if (profile.param1 == 2.0) {
profile.param1 = 0.25 ;
profile.param2 += 0.25 ;
console.log('Reset. param1 =' + profile.param1 + '; param2 increment = '+profile.param2);
}
else{profile.param1 += 0.25 ;}
profile.gui.updateDisplay({verbose : false}) ;
}
I would like to implement this in such a way that the code effectively executes these lines as:
if (profile.xChaos.toFixed(0) > 500.) {
if (profile.x == 2.0) {
profile.x = 0.25 ;
profile.y += 0.25 ;
console.log('Reset. x =' + profile.x + '; y increment = '+profile.y);
}
else{profile.x += 0.25 ;}
profile.gui.updateDisplay({verbose : false}) ;
}
where x,y can be chosen from a set of variables {profile.a, profile.b, profile.c . . .}. I hope this makes it clearer. Thanks.
Make an array of property names, then iterate over that:
const keys = ['x', 'y', 'z'];
for (const key of keys) {
env[key] = env[key] + 2.0;
}
Related
I am trying to make a program which is able to do both decimal to binary and binary to decimal conversions.
I am having trouble with the binary to decimal portion of the code. Forgive me as I know the coding is quite incomplete but I can't figure out where I am going wrong.
Currently I am getting partially correct output in the calculation field (ex. "there is a 1 in the value of (2^0)" and "there is a 2 in the value of (2^1)").
However, when I type 11 as decimal the calculation field is repeating the code twice
(ex. "there is a 1 in the value of (2^0)","there is a 2 in the value of (2^1)","there is a 1 in the value of (2^0)", "there is a 2 in the value of (2^1)").
Obviously it should only give those values once per number.
Also the output field for the actual binary number is incorrect as well, and some of the variables aren't utilized/not needed, but I have been trying to fix the problem of repeating values first before I worked on that.
Any help would be much appreciated!!
function convertByArray(bval) {
var rB = new Array();
var outstr = "";
var p, t, a, o;
o = 0;
for(var i=0; i<bval.length; i++) {
var b = bval.charCodeAt(i);
t = 2;
p = i;
a = t ** p;
if(a === t ** p) {
outstr += a;
}
var bV = b;
$("txtCalc").value += "There is a " + a + " in the value " + "(" + t + "^" + p + ")" + "\n";
o += 1;
b = bV;
$("txtOut").value = outstr;
}
}
You can simply your code if you access the most-significant bit of the bit-string by taking the length (minus one) and subtracting it from the current position. You can access string characters like an array.
var $txtCalc = $(".txtCalc");
var $txtOut = $(".txtOut");
binaryToDecimal("10010101"); // 149
function binaryToDecimal(bval) {
var base = 2, result = 0;
for (var pos = 0; pos < bval.length; pos++) {
var bit = +bval[(bval.length - 1) - pos];
if (bit === 1) {
result += base ** pos;
}
var message = "There is a " + bit + " in the position (" + base + "^" + pos + ")";
$txtCalc.val($txtCalc.val() + message + "\n");
}
$txtOut.val(result);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="txtOut" />
<br />
<textarea class="txtCalc" rows="10" cols="60"></textarea>
Alternatively, you can simply your program to the following. In JavaScript, you can parse any number in any base and format to another base.
var $txtOut = $(".txtOut");
binaryToDecimal("10010101"); // 149
function convertFromBaseToBase(number, fromBase, toBase) {
return parseInt(number, fromBase).toString(toBase);
}
function binaryToDecimal(bval) {
$txtOut.val(convertFromBaseToBase(bval, 2, 10));
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="txtOut" />
not really sure this is possible, cant seem to find any answers that cover it.
Ive found questions on running a math expression that's given as a string and they do the opposite of what im looking for.
basically im debugging my code and want to print out what the expression is to the console. There are currently 30 calculations in various expressions that run each time the code executes and the number is growing.
EG:
var equation = (1 + 5) * (21 x 7);
Ive simplified it as there are variables that are actually parsed for the output.
I want to out put the expression as a string running the calculation but also keep the calculation running for the application.
I am currently concatenating strings and its tedious work so I hoped there might be a better solution than this: as you should see, i do need the variables to work as expected but not the whole expression, thus giving the simplified more readable result above.
This works with varuns answer but not in my case see update below:
var printout = '(' +var1+ ' + ' +var2+ ') * (' +var3+ ' * ' +var4+ ')';
Update based upon Varun's Answer & Comments below it:
var array = [1, 5, 21, 7];
var printout = '(' +array[0]+ ' + ' +array[1]+ ') * (' +array[2]+ ' * ' +array[0]+ ')';
I guess below is the code you are looking for
var eq = `(1 + 5) * (21 * 7)`;
console.log( eq + ' = ' + eval(eq) )
You can also enhance it like this for more dynamic content
var array = [1, 5, 21, 7];
var inp1 = array[0]
var inp2 = array[1]
var inp3 = array[2]
var inp4 = array[3]
var addOperand = "+"
var multiplyOperand = "*"
var eq = `(${inp1} ${addOperand} ${inp2}) ${multiplyOperand} (${inp3} ${multiplyOperand} ${inp4})`;
console.log( eq + ' = ' + eval(eq) )
Since you are using arrays, this is seems scalable and efficient
var array = ['(',1, '+', 5,')', '*','(', 21,'*', 7,')'];
eq = array.join(' ')
console.log( eq + ' = ' + eval(eq) )
Could be more generic but not sure if you need that much only for testing,
here your equation can be any string.
lineNo is the lineNo of your equation inside the function
function calculate(x, y) {
var equation = (x + 5) * (y * 7);
let lineNo = 1
console.log(arguments.callee.toString().split('\n\t')[lineNo].replace(/x/g, x).replace(/y/g, y))
}
calculate(3, 4)
I have an input field that expects a 10 digit number. If the user enters and submits a number less than 10 digits, the function would simply add a "0" until the inputed value is 10 digits in length.
I haven't really used, or understand how recursive functions really work, but I'm basically looking at an efficient way of doing this. One minor issue I'm having is figuring out how to prepend the "0"s at the beginning of the string rather than appended to the end.
My thinking:
function lengthCheck(sQuery) {
for (var i = 0; i < sQuery.length; i++) {
if (sQuery.length !== 10) {
sQuery += "0";
//I'd like to add the 0s to the beggining of the sQuery string.
console.log(sQuery);
lengthCheck(sQuery);
} else return sQuery
}
}
Change:
sQuery += "0"; // added at end of string
to:
sQuery = "0" + sQuery; // added at start of string
To remove the for loop/recursion, you could slice out the desired length in one step:
function padZeros(sQuery) {
// the max amount of zeros you want to lead with
const maxLengthZeros = "0000000000";
// takes the 10 rightmost characters and outputs them in a new string
return (maxLengthZeros + sQuery).slice(-10);
}
Simple generic function using ES6 repeat:
// edge case constraints not implemented for brevity
function padZeros(sQuery = "", maxPadding = 10, outputLength = 10) {
// the max amount of zeros you want to lead with
const maxLengthZeros = "0".repeat(maxPadding);
// returns the "outputLength" rightmost characters
return (maxLengthZeros + sQuery).slice(-outputLength);
}
console.log('padZeros: ' + padZeros("1234567890"));
console.log('padZeros: ' + padZeros("123"));
console.log('padZeros: ' + padZeros(""));
Alternate version that doesn't affect strings over your set limit:
function padZerosIfShort(inputString = "", paddedOutputLength = 10) {
let inputLen = inputString.length;
// only padded if under set length, otherwise returned untouched
return (paddedOutputLength > inputLen)
? "0".repeat(paddedOutputLength - inputLen) + inputString
: inputString;
}
console.log('padZerosIfShort: ' + padZerosIfShort("1234567890", 5));
console.log('padZerosIfShort: ' + padZerosIfShort("123", 5));
console.log('padZerosIfShort: ' + padZerosIfShort("", 5));
It will ultimately depend on your needs how you want to implement this behavior.
The += operator adds things to the end of strings similar to:
sQuery=sQuery+"0"
You can add characters to the front of a string like this
sQuery="0"+sQuery
I also found something interesting here. it works like this:
("00000" + sQuery).slice(-5)
You would add zeros to the front then slice off everything except the last 5. so to get 10 characters you would use:
("0000000000" + n).slice(-10)
You don't need recursion to solve this, just a simple for loop should do the trick. Try this:
function lengthCheck (sQuery) {
for (var i = sQuery.length; i<10; i++) {
sQuery = "0" + sQuery;
}
return sQuery;
}
You're looking to pad the string with zeroes. This is an example I've used before from here and will shorten your code a little bit:
function lengthCheck (sQuery) {
while (sQuery.length < 10)
sQuery = 0 + sQuery;
return sQuery;
}
I believe this has already been answered here (or similar enough to provide you the solution): How to output integers with leading zeros in JavaScript
I am making a calculator in JavaScript and I want to know how to turn a string into an expression.
var numbers = "5+5+6";
numbers = +numbers;
document.querySelector('.screen').innerHTML = numbers;
Adding + before the variable does not seem to work. I would appreciate it if someone helped.
You can use the eval() function like this:
var numbers = "5+5+6";
document.querySelector('.screen').innerHTML = eval(numbers);;
Evaluate/Execute JavaScript code/expressions:
var x = 10;
var y = 20;
var a = eval("x * y") + "<br>";
var b = eval("2 + 2") + "<br>";
var c = eval("x + 17") + "<br>";
var res = a + b + c;
The result of res will be:
200
4
27
Without using eval, which is cheating - you could always write a simple calculator app.
First, take advantage of String.split() as follows
var numbers = "5+5+6";
numbers.split("");
// => ["5","+","5","+","6"]
Now all you need to do is figure out how to evaluate it while keeping the order of operations correct. Hint: it might involve trees.
Try using String.prototype.match() , Array.prototype.reduce() , Number() . See also Chrome App: Doing maths from a string
var numbers = "5+5+6";
var number = numbers.match(/\d+|\+\d+|\-\d+/g)
.reduce(function(a, b) {
return Number(a) + Number(b)
});
document.querySelector(".screen").innerHTML = number;
<div class="screen"></div>
My code speaks for me, I want to wrap array index with another array dynamically (with a loop).
The following code does not work. Please, help me to convert this "x" string to JavaScript code or to find the right way to get the result.
var x = parentTasks[j];
while(x){
x = parentTasks + '[' + numbers + '[' + x + ']]';
}
Later "x" will become undefined, so then loop should stop.
What I expect:
Example when loop is iterated for 1st time:
parentTasks[numbers[parentTasks[j]]]
Example when loop is iterated for 2nd time:
parentTasks[numbers[parentTasks[numbers[parentTasks[j]]]]]
I did it by my self. Here is a solution:
var x = parentTasks[j];
var z = 0
while ( z++ < 2 ) {
x = 'parentTasks[numbers[' + x + ']]';
console.log(eval(x));
}