0

I am trying to dynamically define an object in typeScript with a for loop.

Here is the code for that

        var n = 7 
        interface LooseObject {
            [key: string]: any
        }
        var boardValues: LooseObject = {}
        for (var i = 0; i <= n; i++){
            for(var j = 0; j <= n; j++){
                var boardIndex = 8*(n-i)+j
                boardValues[`n${boardIndex}`] = `n${boardIndex}`
                console.log("generating boardValues",boardValues[`n${boardIndex}`]) //outputs the expected result e.g. n15
            }
        }

Here is a gif showing the output

While running the loop the console.log gives the expected output (e.g. n7). However when I then output the boardValues object created to the console only n16 to n47 are defined. Even weirder is that chrome shows the values as defined properly until I expand the object to see all values and then shows them as undefined.

What am I doing wrong? (I am new to typeScript and not great at programming so sorry for poor practices)

charlie scott
  • 136
  • 1
  • 9
  • Hi, is there any code which runs along/after this code. I tried it [here](https://www.typescriptlang.org/play?#code/G4QwTgBAdhC8EHYICgCWUAuBTMAzEAxlhADID2ZAzlgPIBGAVlgRhAN7IQQDaA1lgE8AXBEoYw6AOYBdESCgDkAX2ShIdMuAAmANRAAbAK5ZKI8lVqNmreGxW4ykABRqIqOBAAMAbjcQAPPBQvqgA1KEAlBxcDmAu4BAMHj6JAUG+DOFRnFwQrhraAJJQWlgAHh4AHABUTlAAtKgRoQw5XAVgugbGlNwABlAAJGwdWsWlZUp90h4Dw6Pj5VNtEARkUJRk+lgAdPpkkk4ARJJYUDggGFIQo3pGJkcANLfdJv1DI5qdi5PTERAAegBZEMGAADqDKBAMAALYjlMHWLBaCBgEyGfSsXaSHbQACMAFYcioVMg1hstrt9ocXvdKBFkEA). It is working fine. – Shivam Singla Mar 13 '21 at 13:17
  • I suspect there is another code that modifies the object after it is created. And for Chrome, when the object is not expanded, Chrome shows a snapshot of the object when it was logged. When you expand the object, it shows the updated value of the object. [Ref](https://stackoverflow.com/questions/11284663/console-log-shows-the-changed-value-of-a-variable-before-the-value-actually-ch) – Shivam Singla Mar 13 '21 at 13:20
  • Thank you for the explanation and the suggestion. I'll have a look at the other code that might interefere. @ShivamSingla. – charlie scott Mar 14 '21 at 12:27

1 Answers1

0

I think your code works fine, it's just that the boardValues properties are not sorted (e.g n50 might be the first key shown, and n7 could be in the middle);

To see all the keys set, try:

console.log(Object.keys(boardValues).sort((a,b)=>Number(a.slice(1))-Number(b.slice(1))))
jeremy302
  • 798
  • 6
  • 10