An array disappears in "for" expression, [duplicate] - javascript

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]);
}
}

Related

Stop passing by reference in closures [duplicate]

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.

Double Dimensional Array in Javascript Returning Undefined Array [duplicate]

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);
}
}

Javascript - Create a method dynamically? [duplicate]

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/

javascript / jquery get value of a variable [duplicate]

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?

how to remove a dom element with javascript? [duplicate]

This question already has answers here:
Removing HTMLCollection elements from the DOM
(5 answers)
Closed 8 years ago.
i have a link and i would like to remove it using javascript
here's what i have so far
test
var a = document.getElementsByTagName('a');
for (var i = 0; i < a.length; ++i) {
if (a[i].innerText === 'test') {
a.remove();
}
}
this will fail.
Don't do it this way. document.getElementsByTagName('a') returns live collection, so loop in reverse order. So try
var aColl = document.getElementsByTagName('a');
for (var i = aColl.length-1; i >= 0; i--) { //loop from reverese order, so that removed item doesn't affect
var thisNode = aColl[i];
if (thisNode.innerHTML === 'test') {
thisNode.parentNode.removeChild(thisNode );
}
}
Fiddle
If you do it for (var i = 0, len = a.length; i < len; i++) { then you end up removing only half of it, since each removal will update the NodeCollection in a and you will end up losing the elements at higher index and your check will fail.

Categories

Resources