skip to Main Content

i have a problem with my svelte code. on the line 41 i have a for loop, which doesn’t run anything, as it doesn’t print out the i variable on the 42 line.

here is my code:

<script>
    import Toolbar from "./toolbar.svelte";
    import Chat from "./chat.svelte";
    var loggedInUser = "dev"
    //database
    var users =
    {
        "dev":{
            "contacts":["Voldemart", "Timur", "Svyat"],
        }
    }

    var chats = {
        0:{"name":"None","members":["Voldemart", "dev"], "messages":[
            {"content":"hi", "sender":"dev"},
            {"content":"pon", "sender":"Voldemart"},
        ]},

        1:{"name":"None","members":["Timur", "dev"], "messages":[
            {"content":"hi", "sender":"dev"},
            {"content":"pon", "sender":"Timur"},
        ]},

        2:{"name":"None","members":["Svyat", "dev"], "messages":[
            {"content":"hi", "sender":"dev"},
            {"content":"pon", "sender":"Svyat"},
        ]},

        3:{"name":"None","members":["Voldemart", "Svyat"], "messages":[
            {"content":"hi", "sender":"Svyat"},
            {"content":"pon", "sender":"Voldemart"},
        ]},
    }

    console.log(chats[0].members.includes(loggedInUser))

    var loggedInUserChats = []
    var i;
    var chatsLength = Object.keys(chats).length
    console.log(chatsLength)
    for (i; i<5; i++) {
        console.log(i)
        if (chats[0].members.includes(loggedInUser)) {
            loggedInUserChats.push(i)
            console.log(i)
        }
    }
    console.log(loggedInUserChats)
</script>
<Toolbar contacts="{users[loggedInUser].contacts}"/>
<div class="chaty">
    <Chat/>
</div>

<style>
    .chaty {
        width: 100%;
        height: 100vh;
        margin-left: 200px;
    }
</style>

i have tried asking gemini, i have tried reading mdn docs and w3schools docs but i found nothing.

2

Answers


  1. You haven’t initialized the variable i. Check it first.
    As i is undefined so it is not going to run for loop try to run the code separately and debug as you like.

    Use this code:

    var i;
    for (i=0; i<5; i++) {
      console.log(i)
    }
    
    Login or Signup to reply.
  2. The issue in your code lies in the for loop where you’re iterating over i. The variable i is not initialized before using it in the loop condition, which can lead to unexpected behavior.

    You need to initialize i before using it in the loop.

    for (i = 0; i < chatsLength; i++) {
        console.log(i);
        if (chats[i].members.includes(loggedInUser)) {
            loggedInUserChats.push(i);
            console.log(i);
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search