JavaScript && JQuery : Iterating - javascript

I have managed to get so far but for some reason, it does not match the last number and run the else command I have in the code.
My current code is:
JavaScript Fiddle
If anyone could point me in the right direction it would be very much appreciated as I've spent the last 2 hours trying to figure this problem out and only managed to get this far.
The next and Previous works fine, along with the View more/less. Its the 'View next address' that the code seems to skip the else.
This code here is always skipped, my question is does anyone know why or can point me in the direction of fixing this?
else {
$(".activee").eq(idx).addClass("hidden");
$(".activee").eq(idx).removeClass("activee").prev().addClass("activee");
alert("Sorry, there is no more addresses to show...");
num[idx]--;
}
Thanks in advance!

Change your fiddle to this:
var num = []; // <-- changed to array from object
for (i = 0; i < leng; i++) { // <-- while i < leng
num.push(i);
}
Updated fiddle

for (i = 0; i == leng; i++) {
num.push(0);
}
you're pushing the value 0 to the num array
probably meant to do
for (i = 0; i == leng; i++) {
num.push(howMany[i]);
}
but I just skimmed the code, so am not sure whether the logic is even valid.

Related

if (i > .length) not working inside for loop (image slider)

First thanks to all the people on this platform! I really appreciate all the help you can get to learn new stuff on the internet. My project is almost completed, I got one last thing that doesn't work properly. I have a for loop which contains code for an image slider. Every image has it's own arrows (right and left) which change by changing the current image. Here's the code inside the for loop:
for (let i = 0 ; i < insMax.length; i++) {
if (i < 1) {
document.getElementsByClassName('arrowleft')[i].removeEventListener('click' , insLeft);
} else {
document.getElementsByClassName('arrowleft')[i].addEventListener('click' , insLeft);
function insLeft() {
document.getElementById('Popup'+i).classList.add("hide");
document.getElementById('Popup'+(i - 1)).classList.remove("hide");
}
}
if (i > insMax.length) {
document.getElementsByClassName('arrowright')[i].removeEventListener('click' , insRight);
} else {
document.getElementsByClassName('arrowright')[i].addEventListener('click' , insRight);
function insRight() {
document.getElementById('Popup'+i).classList.add("hide");
document.getElementById('Popup'+(i + 1)).classList.remove("hide");
}
}
}
The weird thing again is, that the first if statement works as it should. When the first image is active, you can't click anymore on the left arrow. But the right arrow never works since 'Popup'+(i + 1) gets marked as null, which means that the if statement doesn't work. I also tried using if (i > insMax.length - 1) or if (i == insMax.length) but nothing works.
Your loop is defined as:
for (let i = 0 ; i < insMax.length; i++)
Because the condition of the loop is i < insMax.length the value of i will NEVER be greater than or equal to insMax.length. As soon as i equals insMax.length the loop will exit before doing anything inside the loop.
I would suggest you devise something outside this loop to do your check or leverage a while ... or do ... while pattern.

Strange bug in JS code (maybe some variable state caching)

I'm trying to make a small game using JS and Canvas. It is the implementation from old "Stack Attack" 2D platformer from Siemens cellphones.
So I implemented some basic logic to spawn, move around and throw boxes.
Then I came across a very strange bahaviour: sometimes boxes are thrown at the same position within a small time slice, and my special "protecting" function that checks if the column is "available" for throwing at the current moment does not help. Thus the boxes overlap and are going down partly overlapping each other.
I don't know how to efficiently debug this, so I kindly ask to help me with this error. Maybe there is a simple logical mistake in my code that I did not notice.
I made a codepen here: https://codepen.io/anon/pen/ajrqMB
Function moving the boxes down:
function moveColumnDown(pos) {
var b = []
for (var i = 0; i < boxes.length; i++) {
if (boxes[i].x / cw == pos) {
b.push(boxes[i])
}
}
for (var i = 0; i < b.length; i++) {
if (i == 0 && b[i].y < height-3-ch ||
i > 0 && b[i].y + ch < b[i-1].y) {
for (var j = i; j < b.length; j++) {
b[j].y += spd_y
}
break;
}
}
cols_state[pos] = (b.length == 0 || b[b.length-1].y >= y_offset+ch)
}
I'm looking at this code and can't unserstand how even the top overlapping box is going down: the condition i > 0 && b[i].y + ch < b[i-1].y where ch is a single box height should not be satisfied for it anyway...
Also, this line
cols_state[pos] = (b.length == 0 || b[b.length-1].y >= y_offset+ch)
in the end of the function updates the column state. When the box get dropped, column state is set to false. After the box has moved down a little bit in the function moveColumnDown() the state is updated - to false again, I suppose. But still the next box gets dropped for some unknown reason. I thought that maybe they get dropped at the same tick, when the column state is still true - but even in this case assigning false in the drop() function should have mitigated the problem. But the problem still persists.
UPDATE: It seems that the number of dropped boxes in the model doesn't match the real number of displayed boxes (it is much bigger). That's also very strange. On this picture there is 46 boxes (not on the conveyor), but the boxes[] array contains 53 elements.

if else statement in javascript is not working. only in else statement

Sorry, i'm still new here. i just want to know where's my error here. my else statement is not working. but the if statement is working. lets assume that all my variables are correct though my conditional statement isnt. i really need help, im stuck here.
expecting result:
i need to add 13 options for my select. but when my if statement is done, and the else statment will take over the variable hr1, it stop and skip the process. wherein the option is not added.
for example:
hr1 = 9
convertedVar = 20
->it will only add the option when the condition is satisfied, if(hr1 <= convertedVar) and then else will skip.
thank you for you help.
if(a==mod)
{
for(i = 0; i <= 13 ; i++)
{
if(hr1 <= convertedVar)
{
document.getElementById('timeId').options[i] = new Option('---','');
hr1++;
hr2++;
}
else
{
document.getElementById('timeId').options[i] = new Option(h1++ + ':00', hr2++ + ':00');
}
}
}
Don't know much about the logic behind this but this seems a typo to me:
.... s[i] = new Option(h1++ + ':00', hr2 ....
// h1 or hr1 ??
You are incrementing the variable h1 instead of the variable hr1
If h1 isn't known at that time, your loop will stop. As this is the described behavior, 99% sure that this is the error: just a typo.

Having trouble with a for loop not iterating enough

So I have a problem with this FOR loop that I just can't quite figure out. In this case, I know this needs to iterate as least twice. The array, at a minimum, looks something like this...
dTrackerArray = {sParentValue, 1234, sParentValue, 5678}
But for some reason this for loop is only removing one instance instead of all of them.
var check = $.inArray(sParentValue, dTrackerArray);
if (check != -1) {
for(var i = dTrackerArray.length; i > 0; i--) {
if( dTrackerArray[i] === sParentValue ) {
dTrackerArray.splice(i,1);
dTrackerArray.splice(i-1,1);
}
}}
I really appreciate any help I can get here! Thanks!
EDIT: The 2nd splice is to remove the 1234 "associated" with the sParentValue. It seems to work ok.
The problem is in for loop. you start from: var i = dTrackerArray.length and take dTrackerArray[i] this element does not exist. More over you forgot to interate with 0 index element. So you have to change your for loop to:
for(var i = dTrackerArray.length-1; i >= 0; i--)
Easy to miss but you need i >= 0.
EDIT:
Although I think your main issue is that you're modifying an array while your looping. Obviously with my fix you'll get an out of bounds error on the second splice.
var check = $.inArray(sParentValue, dTrackerArray);
if (check != -1) {
for(var i = dTrackerArray.length; i >= 0; i--) {
if( dTrackerArray[i] === sParentValue ) {
dTrackerArray.splice(i,1);
dTrackerArray.splice(i-1,1); //when i == 0 then exception
}
}}
Since you know the format of the array you can do this with a while loop:
var check = $.inArray(sParentValue, dTrackerArray);
while(check > -1)
{
dTrackerArray.splice(check,1);
check = $.inArray(sParentValue, dTrackerArray);
}
You've already stepped through this with a debugger? That's probably all you'd need to do to understand what's happening here. I'd put this in a comment, but I don't have those privileges yet.

javascript issue undefined variable in array

Can someone please tell me what's wrong with this code? Chrome and Firefox are saying that scrns[i] is undefined though Chrome still runs the code on mouseover.
function nextPrev() {
if (!document.getElementsByClassName) return false;
var scrns = document.getElementsByClassName('scrn');
for (var i=0; i<=scrns.length; i++) {
// console.log(i);
scrns[i].onmouseover = function() {
// console.log('foo');
}
}
}
window.onload = nextPrev();
I've tested that the for loop is working and tried to pin down where the problem is coming from in every way I know how. I'm even looking at an example I took from a book sometime ago and cannot understand why scrns[i] would be undefined.
Any help greatly appreciated!
You're using <= when looping through. But remember that arrays are indexed starting at 0, not 1. So an array with 10 elements has a length of 10, but elements 0-9. Change the following:
for (var i=0; i<=scrns.length; i++) {
to:
for (var i=0; i < scrns.length; i++) {
You are looping too far. If i is equal to scrns.length then it is beyond the end of the array. Remove the = in your stop condition:
for (var i=0; i < scrns.length; i++) {
You have an off by one error. Changing <= to < should fix your issue. You can use loop invariants in the future to make sure that you don't go over.
http://en.wikipedia.org/wiki/Loop_invariant
In general though, when looping through an array, begin with the iterating counter at 0 and then loop so long as the counter is less than the length of the array.

Categories

Resources