i = 3;
j = 2;
function domath(x) {
i = 4;
j = 1;
return i*x + j;
}
j = domath(i) - j;
alert(j); //expected result = 11
k = domath(i) + j;
alert(k); //expected result = 15
The above JavaScript code does not return the expected results (as indicated by the comments in the code). Please correct the code for me anyone ?
As you're not using var , the variables i and j you're defining in the first lines are actually the same variable as you define in your domath() function...
try this :
i = 3;
j = 2;
function domath(x) {
var i = 4;
var j = 1;
return i*x + j;
}
j = domath(i) - j;
alert(j); //expected result = 11
k = domath(i) + j;
alert(k); //expected result = 15
P.S : it could be a good idea to vary your variable name in order to make your code more readable
Declare your variables using var:
var i = 3;
var j = 2;
function domath(x) {
var i = 4;
var j = 1;
return i * x + j;
}
It seems to be a really nasty way to do things.
I would personally do something like:
var v1;
var v2;
function math(x){ //do math here then return}
alert(math(1))
If you really have to use the same varible every where at least do it like:
var i = 3;
var j = 2;
function domath(x) {
var i = 4;
var j = 1;
return i*x + j;
}
Also meaningful varibles names will keep you on a good track and using var and not global will also help you!
var i = 3;
var j = 2;
function domath(x) {
var i = 4;
var j = 1;
return i*x + j;
}
var x = domath(i) - j; // overwriting J will change your next expected result
alert(x); //expected result = 11
var k = domath(i) + j;
alert(k); //expected result = 15
The problem is you're overwriting global variables, i.e. screwing up your math:
j = domath(i) - j;
This expression is evaluated from left to right. The call to domath() will assign new values to i and j, so the effective code here would be this:
j = (i = 4) * 3 + 1 - 1;
So once this is done, j will be set to 12, which is indeed not 11. In addition, i will have a value of 4.
To use local variables within your function, you'll have to redeclare them, essentially hiding the global variables being outside this scope:
function domath(x) {
var i = 4;
var j = 1;
return i * x + j;
}
This time, the first assignment will be resolved to this, because domath() won't touch i and j assigned outside:
j = 4 * 3 + 1 - 2
Once this i done, j will be set to 11, just as expected.
To avoid such issues, it's good practice to always use var when defining new variables (which you'll have to do when wanting to write strict code anyway), and not to use such short, not-telling variable names. I'd consider limiting the use of one-character variable names to iterators and other things with very limited scope. Never for something being global.
Related
I have a for loop that i need to increase the value of on each iteration, and a few examples of what I have tried so far. I need to increase the value of tp on each loop through:
for (var t = 9; t < 20; t++) {
//Tried the below:
var timePeriod = report_data[i] + '.tp' + t.toString();
venues[i].scan_times[t] = timePeriod;
//and:
venues[i].scan_times[t] = report_data[i].tp + t;
}
The manual way of doing it, which I am trying to use the for loop to accomplish:
venues[i].scan_times['9'] = report_data[i].tp9;
venues[i].scan_times['10'] = report_data[i].tp10;
....
venues[i].scan_times['19'] = report_data[i].tp19;
venues[i].scan_times['20'] = report_data[i].tp20;
In javascript you can always access attributes in two ways: with bracket notation and dot notation
var myObj = {};
// those 2 lines are equivalent
myObj.a = 1;
myObj['a'] = 1
If you want to dynamically access some attributes you can use whatever you want inside the brackets.
// those 2 lines are equivalent
myObj['a' + 4] = 1;
myObj.a4 = 1;
In your case you can write
for (var t = 9; t < 20; t++) {
venues[i].scan_times[t] = report_data[i]['tp' + t];
}
Can someone tell me why this bit of JavaScript is buggy?
I have HTML also, but I don't want to make this a massive code dump.
<script type = 'text/javascript'>
var playerCards = [];
var dealerCards = [];
function deal() {
var newCard = Math.random() % 12;
var newCard2 = Math.random() % 12;
playerCards += newCard;
playerCards += newCard2;
var counter = 0;
for (var i = 0; i < playerCards.length; ++i) {
counter += i;
}
document.getElementById("playerTotal").innerHTML = counter;
var dCounter = 0;
for (var j = 0; j < playerCards.length; ++j) {
dCounter += j;
}
document.getElementById("dealerTotal").innerHTML = dCounter;
}
</script>
I'm gonna assume this is a silly syntax error someplace, but I can't find it.
I'm guessing that this isn't doing what you expect it to:
playerCards += newCard;
playerCards += newCard2;
Try this instead:
playerCards.push(newCard);
playerCards.push(newCard2);
The first snippet is trying to "add" a number to an array, which doesn't exactly make sense. Through some arcane JavaScript rules, this turns the result into a string.
I'm guessing that you want to concatenate to an array instead.
Math.random returns a number between 0 and 1 - so Math.random() % 12 will probably be zero
var playerCards = [];
playerCards += newCard; //
what are you even trying to do there?
var counter = 0;
for (var i = 0; i < playerCards.length; ++i) {
counter += i;
}
if playerCards had a length, this loop would result in counter having value of 0, 1, 3, 6, 10 .. n(n+1) / 2 - probably not what you intended, but who knows
I know that multi-dimensional arrays are not natively supported in JS, but I would like to shoehorn them in a calculation I'm doing. For example, I have:
amn1 = new Array(4);
for (j = 0; j < amn1.length; j = j + 1) {
amn1[j] = new Array(4);
}
amn1[0][0] = -8.72500;
amn1[0][1] = 1.88000;
amn1[0][2] = 0.741900;
amn1[0][3] = 0.752000;
amn1[1][0] = 0.83090;
amn1[1][1] = 0.11140;
amn1[1][2] = -0.528800;
amn1[1][3] = -0.555890;
amn1[2][0] = -0.13396;
amn1[2][1] = -0.06481;
amn1[2][2] = 0.126423;
amn1[2][3] = 0.128431;
amn1[3][0] = 0.01262;
amn1[3][1] = 0.00540;
amn1[3][2] = -0.009341;
amn1[3][3] = -0.009306;
for (u = 0; u < 4; u = u + 1) {
for (n = 0; n < 4; n = n + 1) {
amn1[u][n] = amn1[u][n] * logt + amn1[u][n];
}
loglambda = loglambda + amn1[u][n];
loglambda = loglambda * logi;
}
Assume my script is linted and all variables are properly declared and initialized. Now, checking to see if JS understands the contents of amn1 in the inner loop, it does. However, in the outer loop a check of the console output reveals undefined. Keeping the logic the same, this works in a procedural language, but not here (I have a working version of this in Fortran).
Why does this not work?
dead simple :
loglambda = loglambda + amn1[u][n];
on that line your N will always be 4.
Keeping in mind the size of your array : you have only j = [0,1,2,3] for each amn1[i][j].
Following code is given:
var a = [ ], i = 0, j = 0;
for (i = 0; i < 5; i += 1) {
(function(c) {
a.push(function () {
console.log(c); });
})(i);
};
for (j = 0; j < 5; j += 1) { a[j](); }
Why does i always get bigger by 1 instead of staying 5? Hasn't the foor loop already been passed, so the i parameter given to the anonymous function should be 5?
If you referenced i from the inner closure then yes, you would see the result being 5 in all cases. However, you pass i by value to the outer function, which is accepted as parameter c. The value of c is then fixed to whatever i was at the moment you created the inner closure.
Consider changing the log statement:
console.log("c:" + c + " i:" + i);
You should see c going from 0 to 4 (inclusive) and i being 5 in all cases.
chhowie's answer is absolutely right (and I upvoted it), but I wanted to show you one more thing to help understand it. Your inner function works similarly to a more explicit function call like this:
var a = [ ], i = 0, j = 0;
function pushFunc(array, c) {
array.push(function () {
console.log(c);
});
}
for (i = 0; i < 5; i += 1) {
pushFunc(array, i);
}
for (j = 0; j < 5; j += 1) { a[j](); }
Which should also help you understand how c comes from the function argument, not from the for loop. Your inner function is doing exactly the same thing as this, just without an externally declared named function.
Is there a shortcut for writing the following 100 assignments?
variable_1 = 1;
variable_2 = 2;
variable_3 = 3;
...
variable_100 = 100;
I have tried
for(var i = 1; i <= 100; i++) {
variable_ + i = i;
}
but I get the error message "Invalid left-hand side in assignment". Any ideas?
Here are a few methods:
Method 1: use eval
Here is the most direct method:
for(var i = 1; i <= 100; i++) {
eval("var variable_" + i + " = " + i);
}
variable_1; // => 1
Disclaimer for the above method: I don't think this problem is a good candidate for using eval. If you do use eval, you should never allow user input to go into what you are evaling, or you could open your site to security risks. That mistake is the main reason people say eval is evil.
Method 2: use dynamically generated object properties
This is a much, much better way:
// If you want these variables to be global, then use `window` (if you're
// in a browser) instead of your own object.
var obj = {};
for(var i = 1; i <= 100; i++) {
obj["variable_" + i] = i;
}
obj.variable_1; // => 1
About the note in the comment about using window to create global variables: I would recommend against this, as it is a quick way to pollute your global scope and step on variables unwittingly.
Method 3: use an array
David suggested using an array. This is another great idea, and, depending on what you are trying to do, may be preferred:
var arr = [];
for(var i = 1; i <= 100; i++) {
arr.push(i);
}
arr[0]; // => 1
This will do it:
for(var i = 1; i <= 100; i++) {
eval("variable_" + i + " = " + i + ";");
}
eval is basically evil, but for such purpose it's OK to use it. (reference)
Live test case.
You are better off using an array
var variable = [];
for (var i=1; i <= 100; i++) {
variable[i] = i;
}
Later, you can access the values using variable[1], variable[2] etc.
If it is like that why not to define array of the objects
var a = new Array();
for(i=0;i<100;i+=)
a[i] = i;
Why not using an array instead like this?
<script language="javascript">
var arrayVar = new Array();
for (var i=0; i<100; i++) {
arrayVar["variable_" + i] = i;
}
</script>
Use an array:
var variable = [];
for(var i = 1; i <= 100; i++) {
variable[i] = i;
}
By way of analogy, you'd want to use an array instead of 100 variables for the same reason you'd want
<div class="variable"></div>
<div class="variable"></div>
<div class="variable"></div>
//and so on
instead of
<div id="variable_1"></div>
<div id="variable_2"></div>
<div id="variable_3"></div>
//and so on
<div id="variable_100"></div>
Invalid left-hand side in assignment
This error gets generated because variable_ + i is an expression. The interpreter thinks you are trying to add two variables instead of concatenating a variable name and a string. An expression cannot be on the left-hand side of an assignment operation.
for(var i = 1; i <= 100; i++) {
window["variable_" + i] = i;
}
alert( variable_50 );
alert( variable_34 );
Assuming you're on a browser you can do:
global[variable] = 'hello'
console.log(variable) -> hello