Array reloop to remove previous set of array data generated - javascript

My file works just fine in the first round of loop when i try to rerun the function again. It shows the previous value of the previous loop when i try to use the value to match and after which it shows the correct value. If i run the function again and again, it keeps holding on to the value of the previous generated random value.
for (var i=0; i<9; i++)
{
var ranD = Math.floor(Math.random()*33);
if (mathStar.indexOf(ranD)== -1) {
mathStar.push(ranD);
item[i].innerHTML = mathStar[i];
}
else {
i--;
}
itemVal[i].value = mathStar[i];
}

Substitute using const and let for var within for loop to avoid creating global variables and --i could have unexpected results within the code where i++ is also used in the foor loop.

Is this the first occurrence of "mathStar"?
If this is the first place you're using mathStar, it means it gets created globally and that usually leads to confusion. In this case, take a look at this.
Looking at just this, it seems that you are not resetting your "mathStar" value. This way, any time you run this loop for the nth time, the values you have added to "mathStar" using mathStar.push(...) also occur in the list of values.

Related

JavaScript For Loop Breaking Early

Why would a for loop terminate early in JavaScript? For some reason my outer for loop terminates after the first repetition. I am new to JavaScript but would expect something like this to work in Java.
function check(){
var elements = document.getElementById('fields').children;
var filteredMolecules = molecules;
console.log(elements.length);
for (i = 0; i < elements.length; i++) {
console.log(elements[i].id)
filterMolecules(filteredMolecules, elements[i].id, 0, 10);
}
}
function filterMolecules(molecules, parameter, lower, upper){
console.log('filtering');
var filteredMolecules = [];
for (i=0;i<molecules.length;i++){
var value = molecules[i].val()[parameter];
filteredMolecules.push(molecules[i]);
}
molecules=filteredMolecules;
}
In check(), I loop through elements which contains 22 items as shown by the first console.log(elements.length). If I remove the method filterMolecules(...) then all 22 IDs are logged. However, with the code as is, only the first id is logged.
I believe the filterMolecules method which should run elements.length number of times is causing the outer for loop to not work. Could someone please explain why this is happening. If relevant, in filterMolecules(...) the data is retrieved from Google Firebase with molecules[i].val()[parameter]. Additionally, both methods use the global variable molecules (line 3 and line 14)
When you don't declare variables in javascript you end up using globals (which can be a difficult to spot source of bugs). So here you are using the same global variable i for both loops. When you start looping thought molecules you are accidentally incrementing the counter loop of your first for. Use different variables or define them with :
for (let i=0;i<molecules.length;i++)
Which will give each loop its own version of i.
In this case, since the declarations are inside individual functions, you could use var too:
for (var i=0;i<molecules.length;i++) {
// etc.
}

Clearing empty element from array

Hello i am not sure why those empty elements still there even i clear (or clear function does not work guess). Might you guys have a look on this. I am getting this array after add another value into same array.I am asking whats is happening behind not just solving code thank you
this is function when ever i click button it adds 4 into DVALUE array.
if("q"+idcount+"d" == this.id){
DVALUE[dcount++] = 4;
// alert("D ARRAY"+DVALUE.toString());
}
And this is when ever i click revert button it will remove last added number
if ("d" === qwer) {
// alert(""+DVALUE.toString());
DVALUE.pop();
cleararrayD(); // also calling this function to remove empty elements when ever this if occurs
}
And this is cleararrayD Function
function cleararrayD() {
lens = DVALUE.length, i;
for (i = 0; i < lens; i++) DVALUE[i] && DVALUE.push(DVALUE[i]); // copy non-empty values to the end of the array
DVALUE.splice(0, lens);
}
I am asking whats is happening behind not just solving code
The .length of DVALUE array does not change at cleararrayD() function call as an element is .push()ed to DVALUE array for each index of DVALUE before .splice() is called with original array .length at second parameter, removing the preceding elements to the elements .push()ed to the array.
Okey i got answer for my question. As you can see it clears array but i put element at wrong indexes. Everytime i click button Dcount++ adding indexes so i just doing this Dcount-- in my removing functions
DVALUE[dcount++] = 4;

JS For Loop Stopping Early after Calling Function

I have a Javascript Array that holds the contents of a page. In order to draw all the objects in the right places when the page loads I loop over the array and pull out the elements. This worked very well until I allowed the objects to have children within them.
The current array structure is
0-> {elements=[] frame={I keep the frame attributes here with key value pairs}}, 1-> {elements=[] frame={}}
However, I just started adding sub-elements to the elements array in each object. So now I have to loop through/draw each element, check to see if there are any children and if so then I have to draw them too.
The problem I'm having is that after I loop through the first 0 object and it's children the for loop stops running. Is it because I'm calling the same function multiple times? I've done that before so I don't think that's what is happening.
this.run_loop = function (spawn, dom) {
console.log(spawn)
alert(spawn.length)
for (i = 0; i < spawn.length; i++) {
console.log(spawn[i])
//alert("i one")
var newdom = dom + "_" + i;
this.synthesize_elements(spawn[i], dom, newdom)
if (spawn[i].hasOwnProperty('elements')) {
//alert("FOUND")
var newarray = spawn[i]['elements'];
if (newarray.length > 0) {
this.run_loop(newarray, newdom)
}
}
}
}
This is a little old but I encountered a similar issue and found my way here, but I figured it out and thought I'd post the solution if anyone else came across this. The issue in my case (and it looks like in your case as well though I can't be sure) was in the declaration of the for loop:
for (i = 0; i < spawn.length; i++)
You're not declaring that i is a new var. so if anything inside the
this.run_loop(newarray, newdom)
function also manipulates a counter variable called i that isn't declared a new var, it will also change the one in your outer scope, and kick you out of the loop if it goes over the length of spawn
just always declare:
for (var i; i< spawn.length; i++)
in your loops or make sure your counters are unique.

JavaScript JSON compare

There are two JSON var (JSON.parse'd already)
var acc http://pastebin.com/7DyfFzTx
var sit http://pastebin.com/vnZiVaDx
My objective is to loop each var to compare acc.items.site_name with sit.items.main_site.name to see if they are equal. If they are equal, then I need to store sit.items.main_site.site_url in a variable. I am using this code:
for(i=0; i < acc.items.length;i++)
{
aname = acc.items[i].site_name;
for(i=0; i < sit.items.length;i++)
{
sname = sit.items[i].main_site.name;
if (aname == sname)
alert("same "+aname);
}
}
But the alert only logs "same Physics" . "Physics" is the first object in acc.items. This means that the loop is only comparing first acc.items but how do I make it compare the second and further on objects (e.g. "TeX - LaTeX")
Well, you can start by using a different control variable for the outer and inner loops. :)
Also, notice how you are running through every element of the second object each time you consider an element in the first object- that doesn't seem like what you want to do.
Try reviewing this posting for a more modular method:
http://jsperf.com/recursive-vs-json-object-comparison
You're using the same variable for the inner and outer loop.
Give the second for loop a different variable name than i

JavaScript Incrementing a number in an array

I want to increment a value in a array when a link is pressed in JavaScript
i Used the following code
<script type="text/javascript">
var i=0;
var numbers = new Array();
function go(val){
numbers[i]=val;
i++;
alert(numbers[i]);
}
</script>
Called the Function like this
<a href='javascript:go(1)' </a>
but always the alert prompts me 'undefined'
The alert is correct -- before you do your alert, you incremented i. You're looking at the next element after the one you just entered.
After calling the method once, your array looks like this:
numbers[0] = 1;
numbers[1] = undefined;
and i == 1.
After calling it again, the array looks like:
numbers[0] = 1;
numbers[1] = 1;
numbers[2] = undefined;
and i == 2.
Hopefully you can see that this method will always alert undefined
That's because you increment "i"
i++;
right before you put up the alert! Thus "i" will alwuays refer to the next array slot to use, not the one you just populated.
You could change the alert to use "i-1"
alert(numbers[i - 1]);
You are setting numbers[0] = 1 and then incrementing i which becomes 1 so alert(numbers[1]) is undefined, because it is undefined.
Do the alert before you increment. Also, use onclick or even better unobtrusively attach the event handlers in JS, not in the HTML.
Yes, it does that because you:
Create a completely empty array, and a pointer at 0.
When the function is called, you set the current pointer value to whatever was passed in...
...and then increment the pointer, so it's now pointing past the end of all the elements.
Now you look at the element in the array that's being pointed at, which has to be undefined because of the way you're managing the i pointer.
What were you hoping for this to do, by the way?
The question doesn't even match the code... or the code doesn't match the question?
"I want to increment a value in a array"
Your code is not incrementing the value, it's incrementing the index!
function go(val){
numbers[i]=val;
i++;
}
(where i is the index of the next undefined array element) is just the same as
numbers.push(val);
and if you need i to equal what will be the index of the next undefined array element then
i = numbers.length;
To increment the value you would have to first have numeric values for some array elements; then your function would need the index of which value to increment
var numbers = [0,0,0,0];
function go(i){
numbers[i]++;
}
// testing
go(1);
go(3);
go(1);
alert(numbers);
will show 0,2,0,1
But if your entire goal is to put a value into a new element on the end of an array then just use .push()
and .length will tell you how many elements there are; there is no need to increment an i

Categories

Resources