Advice for directing further learning

Posted on
  • I've stumbled across a problem that I can't get my head around and am not sure what to search for to learn how to resolve it. Can anyone help name a technique or method which I can read up on?

    I'm trying to access a propety of an object which changes depending on the output of a function. This is a simplified example:

    var days = {
      Monday: {hour: 6, minute: 30},
      Tuesday: {hour: 7, minute: 0},
    };
    
    var today = function() {
      return "Tuesday" // simplified for this example - not sure if return is best approach
    };
    
    console.log(days[today].hour);
    

    Espruino says:

    Uncaught Error: Cannot read property 'hour' of undefined
     at line 1 col 24
    console.log(days[today].hour);
                           ^
    

    Do I need to get today to return a string instead? Any help would be much appreciated.

    This is a situation where I don't know enough to help myself :)

  • @user101594

    in line 10 you pass the function reference of the today function. What you want to use for the property access is the value the function returns... therefore, just execute the function by beating it with () on its butt... ;-) ...give it a kick to get a kick out of it...

    var days = {
      Monday: {hour: 6, minute: 30},
      Tuesday: {hour: 7, minute: 0},
    };
    var today = function() {
      return "Tuesday"; // simplified for this example (yes string is just perfect)
    };
    
    console.log(days[today()].hour);
    
  • Mon 2020.02.03

    @user101594

    'not sure what to search for to learn how to resolve it'

    to learn
    Asking here was a good choice to start the learning process
    Asking there will be the choice to resolve

     
    W3Schools has always been a good place to start:

    Google:   array javascript site:w3schools.com

    https://www.w3schools.com/js/js_arrays.a­sp



    Array String Indexers

    http://www.java2s.com/Tutorial/JavaScrip­t/0220__Array/Usestringasthearrayindexer­.htm

  • Thank you very, very much indeed. This makes sense now, but I couldn't find any examples which illustrated it in usual places (W3, StackOverflow, etc.). Probably wasn't searching for the right terms.

  • I restructured my data in "days" a few times and lost understanding of what I was dealing with. I thought that it was an object as I couldn't reference its contents with an index e.g

    console.log(days[2].hour);
    

    Firefox console says:

    TypeError: days[2] is undefined
    

    If it's an array after all, then I'll do some more reading about arrays. Thanks

  • Tue 2020.02.04

    'I'm trying to access a propety of an object which changes depending on the output of a function'

    I get that some identifier will be returned from the results of a completed task within a function. And, . . . that value will somehow reference items in a list perhaps?



    @user101594 are we attempting to work with an array, or Json Object Notation?

    https://www.w3schools.com/js/js_json_syn­tax.asp

    L1 in code block found in post #1 is creating a Javascript variable whose content is a JSON object.

    Is the attempt to reference that JSON object 'key' by 'name' and extract it's corresponding 'value'?

    . . . or, . . .

    Is the thinking to access an array by it's indexer? Or an array of a two dim array elements by an indexer?

    ref: snippets in post #5


    I'm not at a development station with an active Espruino device connected, doing the following from memory. . . .

    Debug tip should this not yet be understood

    Typing dump() in Left-Hand console should reveal if declared variables are initialized.

    http://www.espruino.com/Reference#l__glo­bal_dump

    ref: second snipper in post #1
    'Uncaught Error: Cannot read property 'hour' of undefined'

    Entering the variable by name days should do the same. This might also provide a clue as to how the Espruino WebIDE sees what is declared and how it is initialized, and might clear up some mental insight.

  • When you have an object with (named) properties - var o = {n:3,s:"str"}, think of the square brackets

    • either as

    • short form of getter and setter methods to access properties n and s with the property name as string "n" and "s":

    o.getN = function() { return this.n; };
    o.setN = function(n) { this.n = n; };
    
    • which you use as, for examples

    o.getN();  o.setS("me");
    
    • that equals to o["n"]; o["s"]="me";

    • or

    • (pseudo) array accessors with arbitrary index, where index is property name as string

    • or

    • map or directory (object) accessors with key, where key is property name as string

    After all, it is just syntax, and the interpreter knows what kind 'thing' it is that is in front of the square brackets:

    • either

    • a real Array object (w/ consecutive, numerically indexed series of adjacent storage slots - then the value in the brackets has to be a number

    • or

    • a real Object (w/ arbitrary, named properties) - then the value in the brackets has to be a property name as string (see also JSON - JavaScript Object Notation - an object declaration in string form: oAsJSONString = '{"n":3,"s":"str"}' - see JSON.stringify(o)/.parse(oAsJsonString) - PS: also supporting arrays... )

    Even though the Array is also an object... it is fundamentally different intrinsic to the implementation and behaves as such differently, even though it has similar looks and analogue functionality - as JSON shows.

    On the other hand, you can think reverse:

    o.n is the short form of o["n"]...

    After all it is just a notation by convention and pure syntax - sugar or salt, what ever you like - that spices up the code... (hence it's name code, coding, codified meaning).

    There is more of the CS Formal Languages theory/philosophy around this... like What are the real, realm specific differences between {n:3,s:"str"} and [3,"str"] and '{"n":3,"s":"str"}' ? ... may be at another post's time...

  • Wed 2020.02.05

    TypeError: days[2] is undefined
    

    re: post #5

    OPTION BASE ZERO   vs   OPTION BASE ONE

    Referencing the element using indexer 2 when there are only two elements using Option Base Zero, will yield undefined as a result, since there is only element zero and element one.

  • If you have an object var o = {n:3,s:"str"}and you try array-access the properties, no matter what numeric value you put into the square bracket, it does not give you properties back... because the number is just another 'name'... but you can use it to add more attributes, for example:

    var o = {n:3,s:"str"};
    console.log("o[1]:", o[1]); // ---> undefined
    o[1]="x1"; // ---> adds new property w/ (numeric)  name ```1``` to object ```o```
              //       and set the properties value to string "x1"
    console.log("o[1]:",o[1]); // ---> access/show property w/ name ```1```: ---> "x1"
    
    
    
    
    o[1]: undefined
    o[1]: x1
    
  • Post a reply
    • Bold
    • Italics
    • Link
    • Image
    • List
    • Quote
    • code
    • Preview
About

Advice for directing further learning

Posted by Avatar for user101594 @user101594

Actions