Home > Blockchain >  Some how My array only goes through exactly 1/2
Some how My array only goes through exactly 1/2

Time:09-24

For some reason what I put in my input tag in my html exactly 1/2 of my array is processed . So my input collects the number/letters and assigns a line of code . for example

let result  = Object.fromEntries(
  Object.entries(answers2).map(([k, v]) => [k, MSamples[v] ])
);

For simplicity sake lets say you put in asdf which would equal


0: ['M20']
1: ['M30']
2:['M40']
3: ['M50']
length 4

so in a for loop

  for (let i = 0; i < Object.keys(result).length; i  ) { }

for some reason it would only print

0: ['M20']
1: ['M30']

Even if you disable all the code in the for statement and only do a console.log('wow') it will only console.log wow two times.

EDIT so people want a reproducible example so here is everything you need.

var MSamples = {
  "A": [
    "M10",
  ],
  "B": [
    "M20",
  ],
  "C": [
    "M30",
  ],
  "D": [
    'M40',
  ],
}

var answers2 = document.getElementById('fname').value;

let result = Object.fromEntries(
  Object.entries(answers2).map(([k, v]) => [k, MSamples[v]])
);

for (let i = 0; i < Object.keys(result).length; i  ) {
  console.log('wow');
}
<form class="form1 " action="">
  <input type="text" id="fname" name="fname" value="ABCD">
</form>

EDIT FOUND THE ANSWER

So it seems the problem is that I can not put i ; . I took out all instances of i ; and it all worked. at the end of my for statement .

CodePudding user response:

I could not reproduce this directly using your example, but I might have an idea of what is going on. Do you have another element somewhere in your DOM with the same id fname?

document.getElementById('fname') will return the first element with that id that it encounters, and if that element's value is two characters long than your code will use that length in the for-loop.

CodePudding user response:

So it seems the problem is that I can not put i ; . I took out all instances of i ; and it all worked. at the end of my for statement ..

  • Related