How to pass loop variable to elements [duplicate] - javascript

This question already has an answer here:
Why is the loop assigning a reference of the last index element to? [duplicate]
(1 answer)
Closed 8 years ago.
Can someone please tell me how can I grab i properly? By now, it's just displaying the same number (the value of a.length when clicking on any anchor element.
var a = document.getElementsByTagName('a');
for (i = 0, j = a.length; i< j;i++) {
a[i].onclick = function() {
console.log(i); //display a.length in all anchors
return false;
}
}

var a = document.getElementsByTagName('a');
for (i = 0, j = a.length; i< j;i++) {
a[i].idx = i;
a[i].onclick = function() {
console.log(this.idx);
return false;
}
}

Related

SUM of all elements of a two-dimensional array [duplicate]

This question already has answers here:
How to return values in javascript
(8 answers)
Closed 2 years ago.
I am trying to solve a challenge from jshero.net. The challenge is:
Write a function sum that calculates the sum of all elements of a
two-dimensional array. sum([[1, 2], [3]]) should return 6.
For this one I need to use a nested loop. The best solution I could come up with is:
function sum(num){
let mySum= [num.length]
var sum = 0;
for (var i = 0; i > mySum; i++) {
for (var j = 0; j > mySum; j++) {
sum =mySum[[i]+[j]];
}
}
}
But when I run the code I get the following error:
sum([[1]]) does not return 1, but undefined.
Test-Error! Correct the error and re-run the tests!
Do you guys have any ideea how to solve this?
I think the function should look something like this:
function sum(arr) {
let sum = 0;
for (let i = 0; i < arr.length; i++) {
for (let j = 0; j < arr[i].length; j++) {
sum += arr[i][j];
}
}
return sum;
}
arr=[[1,2,3,4],5,6,[7,8],9]
var sum=0;
for(var d1 of arr)
if(d1.length) // undefined if not array||number
for(var d2 of d1)
sum+=d2;
else
sum+=d1;
// 45

how to do descending order prime numbers in javascript? [duplicate]

This question already has answers here:
How to reverse an array in Javascript?
(4 answers)
Closed 4 years ago.
There's a way I can "invert" my array of prime numbers? or I have to do in other logic way.
There's my code
var primos = [];
for (var i = 0; i <= 100; i++) {
var fake = false;
for (var j = 2; j <= i; j++) {
if (i%j==0 && j!=i) {
fake = true;
}
}
if (fake === false) {
primos.push(i);
}
}
for(i = primos.length; i > 0; i--) {
console.log(primos[i]);
}
I want the result to be the array but in descending order
Like [97, 89, 83, ...]
If you want to simply revert the result you can use the Array prototype method reverse:
var primos = [];
for (var i = 0; i <= 100; i++) {
var fake = false;
for (var j = 2; j <= i; j++) {
if (i%j==0 && j!=i) {
fake = true;
}
}
if (fake === false) {
primos.push(i);
}
}
primos = primos.reverse();
for(i = primos.length; i > 0; i--) {
console.log(primos[i]);
}
Take a look at this other answer for some ideas on other ways to accomplish this:
How to find prime numbers between 0 - 100?

JavaScript Closure in Loop [duplicate]

This question already has answers here:
JavaScript closure inside loops – simple practical example
(44 answers)
Closed 7 years ago.
I wanted to solve this question posted as a public question on testdome. Each as[i] should be a function that does alert(i).
The code to be bug-fixed is this:
function registerHandlers() {
var as = document.getElementsByTagName('a');
for (i = as.length; i-- >= 0;) {
as[i].onclick = function() {
alert(i);
return false;
}
}
}
The solution I attempted is this:
function registerHandlers() {
var as = document.getElementsByTagName('a');
//made the loop variables more explicit
for (i = as.length-1; i >=0; i--) {
var x = i;
as[x].onclick = function() {
alert(x);
return false;
}
}
}
I though that variable i is persistent, so I kept its copy in variable x, and use variable x instead of i. But it does not solve the problem completely. Please let me know what is my misunderstanding.
Your i and x values are declared in exactly the same scope, so by the time the function is executed x will be its final value. You could create a closure like this:
function registerHandlers() {
var links = document.getElementsByTagName('a');
for (var i = 0, len = links.length; i < len; i += 1) {
links[i].onclick = generateHandler(i);
}
function generateHandler (index) {
return function () {
alert(index);
return false;
}
}
}

Uncaught TypeError: Cannot read property 'addClass' of undefined [duplicate]

This question already has answers here:
JavaScript closure inside loops – simple practical example
(44 answers)
Closed 8 years ago.
What's wrong with this string: items[i].addClass('in'); ? it's killing me! I was tring different ways with .each(); for example but it's still fail...
if(layer = 'aboutAuthor') {
var items = $('.aboutAuthor .item');
var K = 100; // Коэфициент.
var t = K * (items.length + 1);
for (var i = items.length - 1; i >= 0; i--) {
console.log(items[i]);
setTimeout(function(){
items[i].addClass('in');
}, t);
t += K;
}
}
strange moment that console.log() displays each element in logs as expected, and normal. HELP!
I tried to not change the code too much, but I had assumed that you wanted to change the items in reverse.
if(layer === 'aboutAuthor') {
var items = $('.aboutAuthor .item');
var K = 100; // Коэфициент.
var t = K * (items.length + 1);
var i = items.length - 1;
$(items.get().reverse()).each(function() {
var item = $(this);
console.log(item);
setTimeout(function(){
item.addClass('in');
}, t);
t += K;
}
});
}

How to show current loop iteration in click function, javascript [duplicate]

This question already has answers here:
JavaScript closure inside loops – simple practical example
(44 answers)
Closed 8 years ago.
JSFiddle
var arr = [ [0], [1], [2], [3] ];
for ( var i = 0; i < arr.length; i++ ) {
$('#btn-' + i).click(function() {
console.log(i);
});
}
When I'm clicking on corresponding button console.log always shows me last iteration instead of the current iteration. Why?
Try creating a closure, In other words, create a scope per iteration. Now in your code all the event handlers are created in a single scope and the i inside of that scope would get updated instantly to 4. So as a result, when you clicking on all the buttons the result would be same. That is the updated one of i
for ( var i = 0; i < arr.length; i++ ) {
var j = function(x) {
$('#btn-' + x).click(function() {
console.log(x);
});
}
j(i);
}
DEMO
Because of closure! For that you can do this:
for (var i = 0; i < arr.length; i++) {
(function(n) {
$('#btn-' + i).click(function() {
console.log(n);
});
})(i);
}
DEMO

Categories