skip to Main Content

I am trying to make a function that has a for-loop that goes through the array and should write the number 30 on a new document. But, when I call this function nothing happens, but if I remove the ".length" the document writes the number 10. I’m not sure if the problem is in the for loop or the document.write() function

The document.write() is a placeholder im just using that to make sure the code above it is working correctly.

function TryCode() {



  var codelist = [
  ["test1", 10],
  ["test2", 20],
  ["test3", 30],
];


  for (var i = 0; i < codelist.length;) {
    i++
  }


  document.write(codelist[i][1])

}

I tried running it as it is and nothing happend, it didn’t write anything. But when I remove the length it wrote 10. I understand why it would come out as 10 but I don’t understand why adding the .length makes it not work.

2

Answers


  1. Your code has error in for loop it doesn’t correctly iterate through the array, resulting in an attempt to access an invalid index.

    Try this:

    function TryCode() {
        var codelist = [
            ["test1", 10],
            ["test2", 20],
            ["test3", 30],
        ];
    
        for (var i = 0; i < codelist.length; i++) {
            if (codelist[i][1] === 30) {
                document.write(codelist[i][1]);
            }
        }
    }
    
    TryCode();
    
    

    In the code I provided the for loop goes through each item in the "codelist" array. If it finds an item where the second part is 30, it writes that number to the document.

    Login or Signup to reply.
  2. No need to use a for loop here. Simply use forEach which iterates through every element by itself:

    function TryCode() {
      let codelist = [
        ["test1", 10],
        ["test2", 20],
        ["test3", 30],
      ];
    
      codelist.forEach(element => {
        document.write(element[1]);
      }); 
    }
    
    TryCode();
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search