This question already has answers here:
JavaScript closure inside loops – simple practical example
(44 answers)
Closed 8 years ago.
dynobj = {};
methods = ["method1","method2", "method3"];
for (var i = 0; i < methods.length; i++) {
dynobj[methods[i]] = function () {
alert("I am " + i);
};
};
dynobj.method2();
dynobj.method1();
I expect "I am 1" and "I am 0", but have "I am 3" and "I am 3". What the correct way to have behaveary which I expect?
Try the following:
var dynobj = {};
var methods = ["method1", "method2", "method3"];
var length = methods.length;
for (var i = 0; i < length; i++) {
dynobj[methods[i]] = (function (i) {
return function () {
alert("I am " + i);
};
}(i));
}
dynobj.method2();
dynobj.method1();
See the demo: http://jsfiddle.net/3Fxv5/
Related
This question already has answers here:
JavaScript closure inside loops – simple practical example
(44 answers)
Closed 6 years ago.
I was trying to print first array element using recursive function but output is not as expected.
var modelArray = [1,2,3];
var refurbArray = [a,b];
for (var z = 0; z < modelArray.length; z++) {
for (var y = 0; y < refurbArray.length; y++) {
var check = modelArray[z];
var recursive(refurbArray[y], function() {
consol.log(check);
});
}
}
Expected output:
1
1
2
2
3
3
Obtained output:
3
3
3
3
3
3
The problem you are having is that recursive have deferred the call to your call back function (likely due to some async functionality inside the recursive), and the value of check has changed when the callback function is finally executed.
You need to bind the check in a closure, for which there are several options and coding style on how to do, but example like
for (var z = 0; z < modelArray.length; z++) {
for (var y = 0; y < refurbArray.length; y++) {
(function() {
var check = modelArray[z];
recursive(refurbArray[y], function() {
consol.log(check);
});
})();
}
}
Try with something like:
var modelArray = [1,2,3];
var refurbArray = ['a','b'];
function recursive(val, cb){
cb();
}
for (var z = 0; z < modelArray.length; z++) {
for (var y = 0; y < refurbArray.length; y++) {
var check = modelArray[z];
recursive(refurbArray[y], function() {
console.log(check);
});
}
}
You print the check variable in the refurbCallback and that remains set to the last value of var check = modelArray[z];
This question already has answers here:
How do JavaScript closures work?
(86 answers)
Closed 7 years ago.
I have code that looks like this:
var a = [];
for(var i = 0; i < 10; i++) {
a[i] = function() {
console.log(i);
}
}
Unfortunately, it seems that i is being passed by reference, so all the functions in a output 10. How do I make it so that each function outputs the value that i had when it was created? I.e. a[0]() gives 0, a[1]() gives 1, etc.
EDIT: to clarify, I do not want a to store the values 0-9. I want a to store functions that return the values 0-9.
You need to invoke a function (to create a closure that captures your value) which returns a function (the one you want to end up with). Something like this:
var a = [];
for (var i = 0; i < 10; i++) {
a[i] = (function(value) {
return function() {
console.log(value);
}
})(i);
}
var a = [];
for(var i = 0; i < 10; i++) {
a[i] = (function(j) {
return function () {
console.log(j);
}
})(i);
}
A better performing version -
function makeFunction(i) {
return function () {
console.log(i);
}
}
var a = [];
for(var i = 0; i < 10; i++) {
a[i] = makeFunction(i);
}
JSFiddle Demo.
This question already has answers here:
Javascript two dimensional arrays [duplicate]
(6 answers)
Closed 8 years ago.
I have searched alot and cannot get a clear answer to my problem.
var rowCount = 3;
var myCounter = 0;
var myNewArray = new Array();
for (var i = 1; i < rowCount; i++) {
try {
myNewArray[myCounter][0] = i;
myNewArray[myCounter][1] = i;
myCounter = myCounter + 1;
} catch (err) {
alert(err.message);
}
}
it is giving and exception saying myNewArray[myCounter] is undefined. Any idea why? I have seen other post and all have shown to declare the array like this or with new Array([]). Nothing is working.
Need help, in advance thank you.
Currently myNewArray is an array but the elements you are trying to access in it do not yet exist (undefined) so you would need to set these elements as arrays
var rowCount = 3;
var myCounter = 0;
var myNewArray = new Array();
for (var i = 1; i < rowCount; i++) {
try {
//set this element as an array if you want to then access it as an array
myNewArray[myCounter] = [];
myNewArray[myCounter][0] = i;
myNewArray[myCounter][1] = i;
myCounter = myCounter + 1;
} catch (err) {
alert(err.message);
}
}
This question already has answers here:
Javascript "Variable Variables": how to assign variable based on another variable?
(3 answers)
Closed 9 years ago.
In javascript, the way to declare a var is: var msg = 'hello', and it is simply to call msg will get the value of 'hello'
if I am now have a number of var, e.g. msg_1, msg_2 ... msg_n would there be a way to get the value by calling something like
for (var i = 0; i < n; i++)
{
var var_name = 'msg_' + i;
alert (var_name)?
}
DEMO
for (var i = 0; i < 5; i++) {
var var_name = 'msg_' + i;
window[var_name] = i;
console.log(window[var_name]);
}
You should put the values inside an array.
var messages = ["first", "second", "third"];
for (var i = 0; i < n; i++)
{
alert (messages[i])
}
I would suggest use to use array instead of what you are doing.
var myVarialbes= [];
for (var i = 0; i < n; ++i) {
myVarialbes[i] = "some stuff" + i;
}
Here you got a simple method:
var var_name=''; //declare variable only once
for (var i = 0; i < 5; i++) //You should change 5 to n
{
var_name = 'msg_' + i;
alert (var_name.split('_')[1]);
}
function do_test(){
var v1 = "variable 1";
var v2 = "variable 2";
var v3 = "variable 3";
for (i=1;i<4;i++){
var o = eval("v"+i); // you actually need this
alert (o);
}
}
But why don't you use arrays?
This question already has answers here:
JavaScript for loop index strangeness [duplicate]
(3 answers)
Closed 8 years ago.
There's some code, and it's not working.
window.onload = function ()
{
var div = document.getElementById ('main');
var img = div.children;
var i = 1;
//console.log(img[i]);
for (var i=1; i != img.length; i++)
{
img[i].onclick = function ()
{
console.log(img[i]);
}
}
}
Please, explain me Why is img[i] in console.log(img[i]); undefined ?
How this bug can be fixed?
why i!=img.length?
Try change to:
for (var i=0; i < img.length; i++)
{
img[i].onclick = function ()
{
console.log(img[i]);
}
}
You are declaring var two times, remove var 1 = 1;
And assign var i value to zero(0)
for (var i=0; i < img.length; i++)
{
img[i].onclick = function ()
{
console.log(img[i]);
}
}