This question already has answers here:
Javascript infamous Loop issue? [duplicate]
(5 answers)
JavaScript closure inside loops – simple practical example
(44 answers)
Closed 8 years ago.
I want to define several methods from an array of method names like so:
var methodNames = ['foo', 'bar', 'baz'],
randomObject = {}, method;
for( var i = methodNames.length - 1; i >= 0; --i ){
method = methodNames[ i ];
randomObject[ method ] = function(){
console.log( method );
}
}
So that I end up with an object randomObject, which has all the methods defined doing the exact same thing. The problem is, every method logs 'foo' instead of the name of the method being called. How can I make the variable method persist when the method is called?
I can't tell if this is the best way to use a closure, but I think this is working...
UPDATE:
http://jsfiddle.net/ZDrCK/1/
var methodNames = ['foo', 'bar', 'baz'],
randomObject = {},
method;
for (var i = methodNames.length - 1; i >= 0; --i) {
method = methodNames[i];
randomObject[method] = (function(met){
return function () {
console.log(met);
}
})(method);
}
randomObject.baz();
randomObject.bar();
randomObject.foo();
You should wrap it in a self-executing closure:
for (var i = methodNames.length - 1; i >= 0; --i) {
(function(method) {
randomObject[method] = function() {
console.log(method);
};
})(methodNames[i]);
}
Related
This question already has answers here:
JavaScript closure inside loops – simple practical example
(44 answers)
Explanation of `let` and block scoping with for loops
(5 answers)
Closed 7 months ago.
I expect the calling of the first element in the array to print out the number 0. However, it prints 5. Does the function call have access to i of its parent function because I declare i as var? If I declare i as a let variable, it prints 0 as expected.
0-closureBug.js
function makeFunctionArray() {
const arr = []
for (var i = 0; i < 5; i++) {
arr.push(function() { console.log(i) })
}
console.log(i)
return arr
}
const functionArr = makeFunctionArray()
functionArr[0]()
This question already has answers here:
How does `for..of` loop resolve the iterator from an object?
(2 answers)
Closed 4 years ago.
Consider this code.
let array = [1,2,3,4,5]
for(let elem of array) {
console.log(elem)
}
Since here, I am not calling anything like array[Symbol.iterator]().since we can only execute function by putting parenthesis after the expression that evaluates its value. here we are just writing for(let elem of array) how does it execute a function named array[Symbol.iterator] ?
You can test it simply enough by replacing [Symbol.iterator] and see what happens:
let array = [1,2,3,4,5]
array[Symbol.iterator] = function* () {
yield *['Larry', 'Mo', 'Curley'];
};
for(let elem of array) {
console.log(elem)
}
Nice question, Actually the for of loop handler is mapped on for loop handler with a built-in iterator and parameters, for better understanding and using [Symbol.iterator] you can easily test it like the following code:
const iterable1 = new Object();
iterable1[Symbol.iterator] = function* () {
yield 1;
yield 2;
yield 3;
yield 4;
yield 5;
};
const arr = [...iterable1];
for(let elem of arr) {
console.log(elem);
}
For more information read the Docs
This question already has answers here:
Is JavaScript a pass-by-reference or pass-by-value language?
(33 answers)
Closed 6 years ago.
I wrote a for-loop that for some reason refuses to modify a global variable. Instead, it seems to create a local variable that it modifies temporarily. A condensed version of my code is as follows.
var clubsArray = [obj, obj, obj];
//each obj contains a property of "goalsFor" which holds an integer
var madridTotalGoals = 0;
var barcaTotalGoals = 0;
function findTotalGoals(clubsArray, totalGoals) {
for(var i = 0; i < clubsArray.length; i++) {
totalGoals += clubsArray[i].goalsFor;
}
}
findTotalGoals(clubsArray, barcaTotalGoals);
// this loops properly and does the math, but it never changes the value of barcaTotalGoals
In the full code there are numerous arrays that hold "club" objects; each contain a property key "goalsFor", which hold an integer as a value. There are also numerous "totalGoals" variables (two are specified here) that have been declared globally.
Does anyone know why the global variable (e.g. barcaTotalGoals) is not being modified when passed through this function? When I console log each step of this loop, the math is taking place but the result is not being stored. I apologize if this has been asked before but I've searched thoroughly.
The variable you are trying to pass, is passed by value and not reference. So it wont affect the original variable
You can assign the value once the for loop is finished
function findTotalGoals(clubsArray, totalGoals) {
for(var i = 0; i < clubsArray.length; i++) {
totalGoals += clubsArray[i].goalsFor;
}
barcaTotalGoals = totalGoals;
}
You are passing by value instead of by reference...
Instead, you could try like this:
clubsArray = [obj, obj, obj];
var totalGoals = {
madrid: 0,
barca: 0
}
function goalsByCountry(clubsArray, totalGoalsClub) {
for(var i = 0; i < clubsArray.length; i++) {
totalGoals[totalGoalsClub] += clubsArray[i].goalsFor;
}
}
goalsByTeam(clubsArray, 'barca');
This question already has answers here:
What does ':' (colon) do in JavaScript?
(11 answers)
Closed 7 years ago.
I'm seeing : used in JavaScript a good bit and I can not figure out what exactly what its doing. Is it naming something? For example is the function being named onSave? Example is below.
onSave: function() {
var properties = this.getFormData(),
request = this.wfsBody("usa", "usa:pecotest", "geom",
properties);
console.log(request);
this.makeRequest(request);enter code here
There are, as far as I know, four uses of : in JavaScript. The ternary operator, switch statements, labels, and part of JavaScript object creation.
// if a, then f is b. Otherwise it is C.
var f = a? b: c;
// This creates an object. You can now look at the object's `name` property.
var obj = {name: val}
switch(foo)
{
case 1:
// this only happens if foo === 1
break;
}
top: // this is a label
for (i = 0; items.length; i++)
for (j = 0; j < tests.length; i++)
if (!tests[j].pass(items[i])){
allPass = false;
break top; // breaks the outermost loop.
}
You'll see this also in JSON, which is JavaScript object notation:
{
"foo": 1,
"bar": [2,3],
"baz": {
"bat": 4
}
}
That is an object where
obj.foo === 1
obj.bar[0] === 2
obj.bar[1] === 3
obj.baz.bat === 4
The most common use, and certainly what most people expect when they see the above code, is that an object is being created with a property "onStart" which is a function defined as above.
: is used as an = in an object - separating the object property from its value. Objects can also have functions as values. So what you're seeing is:
var obj = {
onSave: function(){}
}
could also be obj.onSave = function(){}
This question already has answers here:
how to access object property using variable [duplicate]
(2 answers)
Closed 7 years ago.
I am trying to use a variable to select from an array:
This works:
var myarray = {bricks:3000, studs:500, shingles:400, tiles:700};
function One() {
alert(myarray.bricks);
}
But this does not work:
var myarray = {bricks:3000, studs:500, shingles:400, tiles:700};
var myvalue = "bricks"
function Two() {
alert(myarray.myvalue);
}
How do I do this properly? Here is a fiddle to show what I am trying to accomplish: https://jsfiddle.net/chrislascelles/xhmx7hgc/2/
Use the [] notation.
var myarray = {bricks:3000, studs:500, shingles:400, tiles:700};
function One() {
alert(myarray.bricks);
}
var myvalue = "bricks" //supplied here to make example work
function Two() {
alert(myarray[myvalue]);
}
Demo
The variable is not an array, it's an object.
To access an element from object using variables you should use Bracket Notation like bellow
alert(myarray[myvalue]);
Fiddle
The only thing you are lacking is the syntax. Here is how it works:
function Two() {
alert(myarray[myvalue]);
}
In javascript, it means the same thing to write these two:
var a = {};
a.foo = "hello";
a["bar"] = "world";
a.bar; // world;
a["foo"]; // hello;