Is there a solution I can use that allows me to define more than one var with the same value in a single step at the start of my funcion?
function myFunction () {
var a,b = 0;
document.write(a) // undefined
document.write(b) // 0
}
Is there an improved way to write a,b = 0; ?
Something like this, however I don't like it.
var var1 = "hello",
var2 = "world",
var3 = 666;
Better
var var1 = "hello";
var var2 = "world";
var var3 = 666;
Please take a look at http://javascript.crockford.com/code.html
You can't do two things at once. You can't declare multiple local variables and assign a single value to all of them at the same time. You can do either of the following
var a = 1,
b = 1;
or
var a,b;
a = b = 1;
What you don't want to do is
var a = b = 1;
because you'll end up with b being a global, and that's no good.
var a = 0, b = 0;
var a = 0, b = a;
An alternate way
var a = b = 0;
Related
There is something like this found in my javascript homework. Is this valid, or did they forget to put the braces?
var squares = [],
SIZE = 3,
EMPTY = " ",
score,
moves,
turn = "X";
There are 6 variables being declared in your code. It has nothing to do with an object.
squares is an array, size is a number (3), empty is a string ( ), score and moves are undefined and turn is a string (X)
Google javascript comma operator
EDIT: Declare variables used in scope
var doStuff = function() {
var i,
c = 2,
stuff = "stuff";
};
Rather than:
var doStuff = function() {
//some code
for( var i = 0; i <= 10; i++ ) {
//
}
//some code
var c = 2;
//some code
//some code
var stuff = "stuff";
};
As it lets developers see all the variables that are declared in that scope at a single glance, rather than having to search through the block to see what vars are being declared/used.
They didn't forget. Your teacher just didn't repeat the term 'var' for every variable.
That's the same as:
var squares = [];
var SIZE = 3;
var EMPTY = " ";
var score;
var moves;
var turn = "X";
I want to write a function which will allow me to "solve" an equation in js.
what I want (not in a programming language):
function f(x) { 1 + x * x }
var z = 2
var y = f(z) //y will be 5 as a number
what I have written in JS:
function P(cfg) { ....
this.equation = "1 + x";
....};
P.prototype.eqn = function(x) {
var tmp = eval(this.equation);
return tmp;
};
....
P.prototype.draw = function() {....
for(var i = 0; i < z; i++)
ctx.lineTo(i, this.eqn(i));
....};
also I've read that using eval in a loop is probably not a good idea, but I have not figured out another way (yet) (JS beginner)...
The problem with this code is, that at least in FF the var tmp will STILL contain the string from this.equation instead of the calculated value.
I would appreciate any further insight very much!
Thank you for your time :)
EDIT: because my question was not formulated very well:
after the execution of line
var tmp = eval(this.equation);
the var tmp will hold a STRING which equals the string this.equation, instead of the desired solution y value.
Also I do not mean solve but evaluate, thanks for that tip :)
Based on your example, I'd say that you want to "evaluate an expression", rather than "solve an equation". For evaluating an expression, you can probably find many tutorials. I'll break it down in brief though. You need to do a few steps.
Starting with your string "1 + x * x", you need to break it into tokens. Specifically, break it down into: "1", "+", "x", "*", "x". At this point, you can substitute your variables ("x") for their literal values ("2"), giving you "1", "+", "2", "*", "2"
Now you need to parse the expression. Based on order of operations PEMDAS you need to create a tree data structure, where parenthetical clauses (stuff surrounded by parenthesis) are executed first, multiplication and division next, and then additions and subtraction last. Parsing is often not an easy task, and you may want to put together a simpler BNF grammar (though you can probably find a grammar for simple math expressions with some googling).
Next, walk the tree, depth first, evaluating the operations as you go up the tree. Once you get to the top of the tree, you have your solution.
If instead you want to "solve an equation", you're going to need something much more sophisticated, like Sage
I have used this expression evaluator before. It seemed to work very well. It allows you to pass expressions into a Parser that returns a function object that can then evaluate inputs.
var expr = Parser.parse("2 ^ x");
expr.evaluate({ x: 3 }); // 8
It supports trig functions (sin, cos, ect...) and other handy built in functions such as abs & ciel.
var expr = Parser.parse("sin(x/2) + cos(x/2)")
expr.evaluate({x: Math.PI / 2}); // 1
Examples: http://silentmatt.com/javascript-expression-evaluator/
Code: https://github.com/silentmatt/js-expression-eval
Note that this lib does not use eval().
Not sure I entirely understand your question but how about:
var makeFunctionOfX = function(src) {
return Function('x', 'return ' + src);
};
Then you can say things like:
var g = makeFunctionOfX('2 * x')
var y = g(3); // y contains 6
The great advantage of this over eval is that the Function we create has no magic ability to see variables in the scope (hence the need to explicitly pass it x as a parameter name).
Using eval is safe if you trust the input from the user, and works just fine. (I have no idea what you mean by "the var tmp will still have the string this.equation".)
function FuncCreator(eqn){ this.eqn = eqn }
FuncCreator.prototype.run = function(x,y,z){ return eval(this.eqn) }
var add1 = new FuncCreator('1+x');
var result = add1.run(41); // 42
var complex = new FuncCreator('Math.sin(x*y) / Math.cos(z)');
var result = complex.run(3,4,5); // -1.891591285331882
If you don't trust the user input, you'll need to actually parse the input and process it yourself. This is non-trivial.
You can use the expression parser from the math.js library and do something like this:
var parser = math.parser();
var f = parser.eval('function f(x) = 1 + x * x');
// use the created function f in expressions:
parser.eval('z = 2'); // 2
parser.eval('y = f(z)'); // 5
// or use the created function f in JavaScript:
var z = 2; // 2
var y = f(z); // 5
Creating functions in math.js is quite currently limited, loops and blocks needed to define more extensive functions are not yet supported.
This is an old thread, but I wrote this equation calculator, this doesn't solve algebraic equations though. There is however a function that will allow you to provide an array containing assigned variables. But this doesn't solve for variables that don't have an assigned value.
I probably haven't permuted every test case scenario, but it seems to work pretty decent.
Edit: This would have to be modified to handle negative numbers. Other than that... works fine.
Here is a fiddle
<!doctype html>
<html>
<head>
<title>Javascript Equation Calculator</title>
</head>
<body>
<input type="button" onclick="main()" value="calculate"><br>
<input type="text" id="userinput"><br>
<span id="result">Ready.</span><br>
<script>
function Calculator(){}
String.prototype.replaceLast = function (what, replacement)
{
var pcs = this.split(what);
var lastPc = pcs.pop();
return pcs.join(what) + replacement + lastPc;
};
function inS(substr, str){return (str.indexOf(substr) > -1);}
function arrayValueOrToken(arr, key, token)
{
if(key in arr)
{
return arr[key];
}
return token;
}
function reduceEquation(inputStr)
{
console.log("reduceEquation Executed-----");
while(hasNest(inputStr))
{
if(hasNest(inputStr))
{
inputStr = inputStr.replace(")(",')*(');
for(var i=0;i<=9;i++)
{
inputStr = inputStr.replace(i+"(",i+'*(');
inputStr = inputStr.replace(")"+i,')*'+i);
}
var s = inputStr.lastIndexOf("(");
var e = 0;
for(i=s;i,inputStr.length;i++){if(inputStr[i]==")"){e=i+1;break;}}
var eq = inputStr.substring(s,e);
var replace = eq;
eq = eq.replace(/[()]/g, '');
var substitution = solveEquation(eq);
inputStr = inputStr.replaceLast(replace,substitution);
}
}
return inputStr;
}
function solveEquation(eq)
{
console.log("solveEquation Executed-----");
eq = doFirstOrder(eq);
eq = doLastOrder(eq);
return eq;
}
function doFirstOrder(eq)
{
console.log("doFirstOrder Executed-----");
for(var i=0;i<eq.length;i++)
{
if(eq[i]=="*"){eq = solve(eq,"*");return doFirstOrder(eq);}
if(eq[i]=='/'){eq = solve(eq,'/');return doFirstOrder(eq);}
}
return eq;
}
function doLastOrder(eq)
{
console.log("doLastOrder Executed-----");
for(var i=0;i<eq.length;i++)
{
if(eq[i]=="+"){eq = solve(eq,"+");return doLastOrder(eq);}
if(eq[i]=="-"){eq = solve(eq,"-");return doLastOrder(eq);}
}
return eq;
}
function solve(eq, operator)
{
var setOp = operator;
console.log("solve Executed-----");
var buildEq = "",var1 = true,done = false,char="";
var operators = "+-/*";
var ops = operators.replace(operator, '').split('');
var a=ops[0];
var b=ops[1];
var c=ops[2];
for(var i=0;i<eq.length;i++)
{
char = eq[i];
switch(true)
{
case(char==operator):if(var1===true){var1 = false;}else{done = true;}break;
case(char==a):
case(char==b):
case(char==c):if(var1){char = ""; buildEq = "";}else{done = true;}
}
if(done){break;}
buildEq = buildEq + char;
}
var parts = parts = buildEq.split(operator);
var solution = null;
if(operator=="+"){solution = parseFloat(parts[0]) + parseFloat(parts[1]);}
if(operator=="-"){solution = parseFloat(parts[0]) - parseFloat(parts[1]);}
if(operator=="*"){solution = parseFloat(parts[0]) * parseFloat(parts[1]);}
if(operator=="/"){solution = parseFloat(parts[0]) / parseFloat(parts[1]);}
return eq.replace(buildEq, solution);
}
function hasNest(inputStr){return inS("(",inputStr);}
function allNestsComplete(inputStr)
{
var oC = 0, cC = 0,char="";
for(var i=0;i<inputStr.length;i++){char = inputStr[i];if(char=="("){oC+=1;}if(char==")"){cC+=1;}}
return (oC==cC);
}
Calculator.prototype.calc = function(inputStr)
{
console.log("Calc Executed-----");
inputStr = inputStr.replace(/ /g, "");
inputStr = inputStr.replace(/\\/g, '/');
inputStr = inputStr.replace(/x/g, "*")
inputStr = inputStr.replace(/X/g, "*")
if(!allNestsComplete(inputStr)){return "Nested operations not opened/closed properly.";}
inputStr=reduceEquation(inputStr);
inputStr = solveEquation(inputStr);
return inputStr;
};
Calculator.prototype.calcWithVars = function(inputList)
{
if(inputList.length < 2){return "One or more missing arguments!";}
var vars = [];
var assocVars = [];
var lastVarIndex = inputList.length - 2;
var i = 0;
var inputStr = inputList[inputList.length-1];
for(i=0;i<=lastVarIndex;i++)
{
vars.push(inputList[i].replace(/ /g, ""));
}
for(i=0;i<=vars.length-1;i++)
{
var vParts = vars[i].split("=");
var vName = vParts[0];
var vValue = vParts[1];
assocVars[vName] = vValue;
}
inputStr = inputStr.replace(/ /g, "");
var eqVars = inputStr.replace(/\s+/g, ' ').replace(/[^a-zA-Z-]/g, ' ').replace(/\s\s+/g, ' ');
if(inS(" ", eqVars))
{
eqVars = eqVars.split(" ");
}
else{eqVars = [eqVars];}
eqVars.sort(function(a, b){return a.length - a.length;});
var tempTokens = [];
var tempCount = 1;
for(i=0;i<eqVars.length;i++)
{
var eqVname = eqVars[i];
var substitution = arrayValueOrToken(assocVars, eqVname, "<unknown>");
if(substitution != "<unknown>")
{
inputStr = inputStr.replace(eqVname,substitution);
}
else
{
var tempToken = "#______#"+tempCount+"#______#";
tempCount++;
tempTokens.push(tempToken + "?" + eqVname);
inputStr = inputStr.replace(eqVname,tempToken);
}
}
for(i=0;i<tempTokens.length;i++)
{
var tokenSet = tempTokens[i];
var tokenParts = tokenSet.split("?");
var token = tokenParts[0];
var variableName = tokenParts[1];
inputStr = inputStr.replace(token,variableName);
}
var answerName = "<unknown>";
var eq = inputStr;
if(inS("=", inputStr))
{
var eqParts = inputStr.split("=");
answerName = eqParts[0];
eq = eqParts[1];
}
eq = this.calc(eq);
var result = [];
for(i=0;i<eqVars.length;i++)
{
var v = arrayValueOrToken(assocVars, eqVars[i], "<unknown>");
if(v != "<unknown>")
{
result.push(assocVars[eqVars[i]]);
}
}
result.push(eq);
return result;
};
function main()
{
var calculator = new Calculator();
elUserInput = document.getElementById('userinput');
console.log("input: "+ elUserInput.value);
elResult = document.getElementById('result');
equation = elUserInput.value;
result = calculator.calc(equation);
console.log("result: "+ result);
elResult.innerHTML = result;
}
</script>
</body>
</html>
I want my code to display 170, 122 . All the values have been set in Javascript but still I am not getting the output.
<!DOCTYPE html>
<html>
<body>
<button onclick="UidToPost()">Get It</button>
<script>
var SetUid1 = "170";
var SetUid2 = "122";
var SetUid3 = "135";
var SetUid4 = "144";
var c = 0;
var timingToSend;
var SetUid;
function UidToPost() {
c = c + 1;
var postTo = "SetUid" + c + "";
document.getElementById("do").innerHTML = postTo;
timingToSend = setTimeout('UidToPost()', 1000);
};
</script>
<p id="do"></p>
</body>
</html>
Thanks in advance.
This is the code that I am using
var SetUid = [ "170", "122", "135", "144" ];
var c = 0;
var timingToSend;
function UidToPost() {
var postTo = SetUid[c++];
document.getElementById("do").innerHTML = postTo;
if (c < SetUid.length)
timingToSend = setTimeout(UidToPost, 1000);
};
Use an array instead of discreet variables;
var SetUid = [ "170", "122", "135", "144" ];
var c = 0;
var timingToSend;
function UidToPost() {
var postTo = SetUid[c++];
document.getElementById("do").innerHTML = postTo;
if (c < SetUid.length)
timingToSend = setTimeout(UidToPost, 1000);
};
You're trying to dynamically create the name of the variable to use with string concatenation, which is possible but not with that syntax. Since your variables are global variables, they'll be stored in the window object, so you can access them like this:
window["SetUid1"]
window["setUid2"]
//etc
With that in mind, you'll simply need to change this line:
var postTo = "SetUid" + c + "";
to:
var postTo = window["SetUid" + c];
You'll also need to handle the case where that variable doesn't exist (i.e. they click the button again after the last variable has been displayed), and take appropriate action (probably cycle back to the beginning).
Here is a working demo.
document.getElementById("do").innerHTML = window[postTo];
You should also get in the habit of avoiding the string argument version of setTimeout as it can cause security issues:
timingToSend = setTimeout(UidToPost, 1000);
I presume you'll also want to call clearTimeout() (or avoid setting the last one in the first place), e.g., after your variables are finished.
Finally, this might have been done more easily and flexibly with an array, but the above is how you can do it with your current approach.
This will do the trick:
document.getElementById("do").innerHTML = window[postTo];
You still have to perform a check for the number of vars. Now after the 4th var is displayed, the function will now write "undefined" to the screen because you keep looping.
The reason this is not working, is that you're concatenating the string SetUid with the current count c to make a string, and adding that to the innerHTML of the div.
Instead, you should hold your values in an array and use your variable c as an index to that array:
var values = [170,122,135,144]
var c = -1;
var timingToSend;
var SetUid;
function UidToPost() {
c = (c + 1) % values.length;
var postTo = "SetUid" + c + "";
document.getElementById("do").innerHTML = values[c];
timingToSend = setTimeout('UidToPost()', 1000);
}
Live example: http://jsfiddle.net/RsKZj/
I have a cookie called "login" that contains a structure like "username|hashcode|salt".
Here's my code:
function readTheCookie(the_info)
{
var the_cookie = document.cookie;
var the_cookie = unescape(the_cookie);
var broken_cookie2 = the_cookie.substr(6);
alert(broken_cookie2);
}
readTheCookie('login');
I'ts giving me
pickup22|d47f45d141bf4ecc999ec4c083e28cf7|4ece9bce292e1
Now I just want the first part (everything before the first pipe , in that case, I want pickup22)
How can I do that? Cause the username will never be the same, so I cant put a "fixed" lenght.
Any help appreciated!
var readTheCookie = function (the_info) {
var the_cookie = document.cookie.split(";"), a = the_cookie.length, b;
for (b = 0; b < a; b += 1) {
if (the_cookie[b].substr(0, the_info.length) === the_info) {
return the_cookie.split("=")[1].split("|")[0];
}
}
if (b === a) {
return "";
}
},
username = readTheCookie('login');
That is nice and compact, plus easy to read, and finally it is JSLint compliant. Enjoy!
best way is to use split() method.
var parts = new Array();
parts = broken_cookie2.split("|");
var username = parts[0];
var hashcode = parts[1];
var salt = parts[2];
Reading documentation online, I'm getting confused how to properly define multiple JavaScript variables on a single line.
If I want to condense the following code, what's the proper JavaScript "strict" way to define multiple javascript variables on a single line?
var a = 0;
var b = 0;
Is it:
var a = b = 0;
or
var a = var b = 0;
etc...
Using Javascript's es6 or node, you can do the following:
var [a,b,c,d] = [0,1,2,3]
And if you want to easily print multiple variables in a single line, just do this:
console.log(a, b, c, d)
0 1 2 3
This is similar to #alex gray 's answer here, but this example is in Javascript instead of CoffeeScript.
Note that this uses Javascript's array destructuring assignment
You want to rely on commas because if you rely on the multiple assignment construct, you'll shoot yourself in the foot at one point or another.
An example would be:
>>> var a = b = c = [];
>>> c.push(1)
[1]
>>> a
[1]
They all refer to the same object in memory, they are not "unique" since anytime you make a reference to an object ( array, object literal, function ) it's passed by reference and not value. So if you change just one of those variables, and wanted them to act individually you will not get what you want because they are not individual objects.
There is also a downside in multiple assignment, in that the secondary variables become globals, and you don't want to leak into the global namespace.
(function() { var a = global = 5 })();
alert(window.global) // 5
It's best to just use commas and preferably with lots of whitespace so it's readable:
var a = 5
, b = 2
, c = 3
, d = {}
, e = [];
There is no way to do it in one line with assignment as value.
var a = b = 0;
makes b global. A correct way (without leaking variables) is the slightly longer:
var a = 0, b = a;
which is useful in the case:
var a = <someLargeExpressionHere>, b = a, c = a, d = a;
Why not doing it in two lines?
var a, b, c, d; // All in the same scope
a = b = c = d = 1; // Set value to all.
The reason why, is to preserve the local scope on variable declarations, as this:
var a = b = c = d = 1;
will lead to the implicit declarations of b, c and d on the window scope.
Here is the new ES6 method of declaration multiple variables in one line:
const person = { name: 'Prince', age: 22, id: 1 };
let {name, age, id} = person;
console.log(name);
console.log(age);
console.log(id);
* Your variable name and object index need be same
Specifically to what the OP has asked, if you want to initialize N variables with the same value (e.g. 0), you can use array destructuring and Array.fill to assign to the variables an array of N 0s:
let [a, b, c, d] = Array(4).fill(0);
console.log(a, b, c, d);
note you can only do this with Numbers and Strings
you could do...
var a, b, c; a = b = c = 0; //but why?
c++;
// c = 1, b = 0, a = 0;
do this if they have same value
let x = y = z = 0
otherwise
let [x, y, z] = [10, 30, 50]
console.log(x, y, z) // 10 30 50
The compressed type of that is here:
var a, b = a = "Hi";
& for 3 variables:
var x, y, z = x = y = "Hello";
Hope to be helpful!
This is completely correct:
var str1 = str2 = str3 = "value";
And if change one of their value, the value of other variables won't change:
var str1 = str2 = str3 = "value";
/* Changing value of str2 */
str2 = "Hi Web!";
document.write("str1 = " + str1 + " - str2 = " + str2 + " - str3 = " + str3);