To iterate with for of loop

Hello
In the following code I tried to iterate through strings with for of loop.
It iterates through the first string but not the second. What do I miss?

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script>
      function uff(a) {
        const table = {};
        for (let char of a.replace(/\W/g, "").toLowerCase()) {
          table[char] = table[char] + 1 || 1;
          console.log(table);
        }
      }
      uff("hello sun", "ebket");
    </script>
  </body>
</html>

Thanks:)

Your function is only expecting one argument, so ignores the second one. You could either amend your function to accept two arguments, or pass an array as the argument and then iterate it with the for ... of loop inside it.

Hello
I have done it:

 function uff(a, b) {
        const table = {};
        for (let char of (a, b).replace(/\W/g, "").toLowerCase()) {
          table[char] = table[char] + 1 || 1;
          console.log(table);
        }
      }
      uff("hello sun", "ebket");

My problem is that I would like to use the letters as keys and I want to give
a value to each of them, basically count them . This way I got only the second string, but not the first if I console.log (table).

During the day I was thinking about using the rest operator or argument somehow to make it automatic to accept any arguments.

Why not simply try this then?

function uff(...args) {
  const table = {};
  for (let i=0; i<args.length; i++) {
    for (let char of (args[i]).replace(/\W/g, "").toLowerCase()) {
      table[char] = table[char] + 1 || 1;
      console.log(table);
    }
  }
}

uff("hello sun", "ebket", "zaporizhzhia");

A simple iterative loop which will work through any number of arguments, and your code is nested inside it.

Hello
Thanks for your help. I think I misunderstood for of loop and tried to solve the problem with just one iteration.
:+1:

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.