Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Page 2 of 3 FirstFirst 123 LastLast
Results 16 to 30 of 36
  1. #16
    Master Coder felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    6,454
    Thanks
    0
    Thanked 632 Times in 622 Posts
    Code:
    (function(){               // starts the function
      var manifest = {         // sets up the array-like Object "manifest"
      a:                       // sets the Object "manifest" key to "a"
        {                      // begin property list for "a"
          filename:"01.jpg",   // adds property 'filename' with value '01.jpg' to key "a"
          aphorism: "old",     // adds property 'aphorism' with value 'old' to key "a"
          dog:"spot"           // adds property 'dog' with value 'spot' to key "a"
        }                      // end property list for "a"
      }
    
      var str = manifest.a.filename+'\n';
          str += manifest.a.aphorism+'\n';
          str += manifest.a.dog;
      alert(str);
    })();
    Stephen
    Learn Modern JavaScript - http://javascriptexample.net/
    Helping others to solve their computer problem at http://www.felgall.com/

    Don't forget to start your JavaScript code with "use strict"; which makes it easier to find errors in your code.

  2. #17
    New Coder
    Join Date
    Aug 2013
    Posts
    50
    Thanks
    0
    Thanked 11 Times in 11 Posts
    Quote Originally Posted by jmrker View Post
    I moved it inside the function.
    I thought the onload would invoke it, but nothing happened.
    Oh... nope. It's just a function declaration, but no reference to it is kept (e.g., in a variable, the function has no name).


    Quote Originally Posted by jmrker View Post
    What is the action to invoke it and see some output via the alert?
    Well he had this
    Code:
    (function () {
        // code
    });
    That is a function, but it's not being called/invoked. To invoke it (and make it an IIFE), just add () to it like this:

    Code:
    (function () {
        // code
    })();
    There are different ways of invoking functions. I won't go over the way Douglas Crockford does it or the other ways because it really doesn't matter too much in this case.

    -----------------------------

    As for seeing output, what felgall put works fine.
    You could also use
    alert( JSON.parse(manifest) );
    but it's up to you, really.

  3. #18
    Senior Coder jmrker's Avatar
    Join Date
    Aug 2006
    Location
    FL
    Posts
    3,026
    Thanks
    36
    Thanked 494 Times in 488 Posts
    Thank you 'felgall' and 'joesimmons' for pointing out the (); at the end to invoke the function.

    I tried the:
    alert( JSON.parse(manifest) );
    suggestion, but that did not show anything
    other than "unexpected character" in the error console.

  4. #19
    Master Coder felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    6,454
    Thanks
    0
    Thanked 632 Times in 622 Posts
    Quote Originally Posted by jmrker View Post
    I tried the:
    alert( JSON.parse(manifest) );
    suggestion, but that did not show anything
    other than "unexpected character" in the error console.
    Which browser are you using - older versions of IE do not run the latest version of JavaScript and the JSON object was only added a few years ago.
    Stephen
    Learn Modern JavaScript - http://javascriptexample.net/
    Helping others to solve their computer problem at http://www.felgall.com/

    Don't forget to start your JavaScript code with "use strict"; which makes it easier to find errors in your code.

  5. #20
    Senior Coder jmrker's Avatar
    Join Date
    Aug 2006
    Location
    FL
    Posts
    3,026
    Thanks
    36
    Thanked 494 Times in 488 Posts

    Arrow

    Quote Originally Posted by felgall View Post
    Which browser are you using - older versions of IE do not run the latest version of JavaScript and the JSON object was only added a few years ago.
    Latest (?) version of FF.

  6. #21
    New Coder
    Join Date
    Jan 2013
    Location
    Florida
    Posts
    75
    Thanks
    2
    Thanked 0 Times in 0 Posts
    thank you all for the comments. it is encouraging that i'm starting to get the lingo down.

    as far as the "array like object", i got that terminology from : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys

    in the examples section. it's probably old, but when i was studying it, it did kind of look like an array to me. but i'm not married to it, so i'll just use "object".

    it looks as tho my leaving that alert in there caused a little confusion. i was just using that to walk my way through the code (moving it around) to try and figure out how "each" works.

    the var str stuff. good good good (he said happily rubbing his hands together). something that i have never seen before, fairly simple and something i may be able to noodle out. i had seen this before :alert(manifest['a'].aphorism);
    and the brackets i had put down as related to an array. but i guess you get your choice of how to call up the value in "a" that you want ( ['a'] or .a. ). and the /n is a line feed. and the += is an incrementor. x += 1 means the value of x increases by 1. it seems like using += after a variable name allows for a list of values for the variable to be stored somewhere, and then called by the alert statement.

    is that the idea ? that is neat.

  7. #22
    Senior Coder jmrker's Avatar
    Join Date
    Aug 2006
    Location
    FL
    Posts
    3,026
    Thanks
    36
    Thanked 494 Times in 488 Posts
    The += act two different ways:

    1. As a number increment.
    You could
    x = 0
    x += 1
    or x += 20
    etc.

    2. As a concatenation action.
    str = 'A string';
    str += ' and MORE added to the string'

    alert the results of either operation to see the effects.
    Last edited by jmrker; 08-10-2013 at 01:41 PM.

  8. #23
    New Coder
    Join Date
    Jan 2013
    Location
    Florida
    Posts
    75
    Thanks
    2
    Thanked 0 Times in 0 Posts
    ok. i did. yes, i see. so maybe i should have concluded that alert(variable name) will list all the values that have been assigned to it, as long as a concat was used. i did some monkeying around (no +) and noticed that if i assign 3 different values :
    Code:
    var str = manifest.a.aphorism+'\n';
    str = manifest.a.filename+'\n'+'\n'+'\n';
    str = manifest.a.dog;
    alert(str);
    only the last value is reported (as expected).

    still slightly unsure. from your example, i think the value of str has been modified and is now the concated value. but in this form (with +=) :
    Code:
    var str = manifest.a.aphorism;
          str += manifest.a.filename;
          str += manifest.a.dog;
    alert(str);
    does the alert look for each instance of str ? and is the value of str now "
    old01.jpgspot "?

    your help is appreciated.

  9. #24
    New Coder
    Join Date
    Aug 2013
    Posts
    50
    Thanks
    0
    Thanked 11 Times in 11 Posts
    Quote Originally Posted by jmrker View Post
    I tried the:
    alert( JSON.parse(manifest) );
    suggestion, but that did not show anything
    other than "unexpected character" in the error console.
    Can you show your full code? (Pastebin, please).



    Quote Originally Posted by pratto View Post
    as far as the "array like object", i got that terminology from : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys

    in the examples section. it's probably old, but when i was studying it, it did kind of look like an array to me. but i'm not married to it, so i'll just use "object".
    I don't want to confuse you but I'll lay it out to you as simply as I can put it.
    Arrays are actually Objects in JavaScript. That's why we don't need to define their length. They are objects with number value keys. Of course, they inherit different methods (like array.push for arrays, etc).
    Just think of them as arrays for now, wouldn't want to confuse anyone else. That's mostly correct anyhow. Then, later down the line, you can learn exactly what I meant above.




    Quote Originally Posted by pratto View Post
    i had seen this before :alert(manifest['a'].aphorism);
    and the brackets i had put down as related to an array. but i guess you get your choice of how to call up the value in "a" that you want ( ['a'] or .a. )
    Those brackets are called 'subscript notation'. And I just call the other way 'dot notation', as do many others.

    You can use them if you need dynamism or need to get integer keys from objects.
    e.g., object['5']; // can't use object.5

    Another example of when you would need subscript notation (without rewriting. it's just an example).
    Code:
    // declare an object with 3 key:value pairs
    var numbers = {
        '1' : 'one',
        '2' : 'two',
        '3' : 'three'
    };
    
    // get a number from the user
    var selection = prompt('Enter 1, 2, or 3.');
    
    // use subscript notation to get the word
    // value associated with the number entered
    var word = numbers[selection];
    
    alert(selection + ' is ' + word);
    this (by Douglas Crockford) is a good read if you haven't read it already.




    Quote Originally Posted by pratto View Post
    /n is a line feed.
    Actually \n is a line feed, with a backslash.
    \r is a carriage return





    Quote Originally Posted by pratto View Post
    the += is an incrementor. x += 1 means the value of x increases by 1. it seems like using += after a variable name allows for a list of values for the variable to be stored somewhere, and then called by the alert statement.
    I don't like how they used the plus sign for multiple uses. It confuses people, as per this example.
    The binary operator (plus sign) can either mean addition, concatenation (adjoining, usually strings), or conversion to a number type (confusing, I know. forget about this one for now).

    += is an assignment operator. In your case, it took the previous value of the variable and added to it.


    a += 1;
    is the same as
    a = a + 1;



    It can also do strings
    Code:
    var a = 'hello ';
    a += 'world';
    alert(a);   // 'hello world'
    that is the same as this
    Code:
    var a = 'hello ';
    a = a + 'world';
    alert(a);   // 'hello world'


    You should take a look at the page Expressions and Operators. It should clear some things up.






    Quote Originally Posted by pratto View Post
    ok. i did. yes, i see. so maybe i should have concluded that alert(variable name) will list all the values that have been assigned to it, as long as a concat was used.
    alert() doesn't look outside itself for any values. It looks at the one variable to which you pass it.
    What's happening is you're adding to the variable with +=, just making it a longer string/text. Then alert will tell you the current value at that time.

    Think of the variable as a basket.
    basket = '';
    we will start off with an empty basket (string)
    basket += 'orange ';
    ok now we have an orange in the basket
    basket += 'apple ';
    now we have both an orange and an apple, because we added an apple.
    basket += 'grape ';
    now, as you can guess, we have an orange, apple, and a grape only in one basket.
    now if we send this basket to alert, it will tell us we have all three.
    alert(basket);

  10. #25
    Senior Coder jmrker's Avatar
    Join Date
    Aug 2006
    Location
    FL
    Posts
    3,026
    Thanks
    36
    Thanked 494 Times in 488 Posts
    If you do a bunch of assignments, after initialization, of += to a variable,
    but then use an = only on the variable, only the last assignment is retained.

  11. #26
    New Coder
    Join Date
    Jan 2013
    Location
    Florida
    Posts
    75
    Thanks
    2
    Thanked 0 Times in 0 Posts
    joe - while it is fresh in my mind, let me initially ask you about the last point (i have 2 or 3 other questions relating to earlier points you made that i will post).

    it seems clear to me that the \n is what is causing my confusion. when it is in, alert seems to look at the first value of str, then the next, then the last.

    but that is wrong isn't it? the value of str is the concated value. but how does the 3 separate values on 3 lines happen ?
    Last edited by pratto; 08-10-2013 at 02:46 PM.

  12. #27
    New Coder
    Join Date
    Aug 2013
    Posts
    50
    Thanks
    0
    Thanked 11 Times in 11 Posts
    Quote Originally Posted by pratto View Post
    it seems clear to me that the \n is what is causing my confusion?
    Possibly. The \n is just a new line character. So in alert, you may be thinking that because your values are visually separated by a new line, that alert() looked at every concatenation but it just displays visually the string you pass it. Maybe you should take a basic JavaScript tutorial; YouTube is a good place for that.





    Quote Originally Posted by pratto View Post
    when it is in, alert seems to look at the first value of str, then the next, then the last.
    I think you're overly complicating this. str is just a string, not 3 different values. The value of the one variable is getting modified each line. Then alert() just tells you the value of that one variable; it doesn't look at each time it was lengthened.




    Quote Originally Posted by pratto View Post
    but that is wrong isn't it? the value of str is the concated value. but how does the 3 separate values on 3 lines happen ?
    Well, you don't need 3 lines to do it. That's just possible because of the language. There are many other ways to make that same string.
    You could do it like this:
    Code:
    var str = manifest.a.filename + '\n' + manifest.a.aphorism + '\n' + manifest.a.dog;
    alert(str);
    It works just the same.
    alert() tells you the value of the string you pass it, which in this case is the filename plus a new line plus aphorism plus a new line plus dog.

  13. #28
    Senior Coder jmrker's Avatar
    Join Date
    Aug 2006
    Location
    FL
    Posts
    3,026
    Thanks
    36
    Thanked 494 Times in 488 Posts

    Arrow

    Quote Originally Posted by jmrker View Post
    Thank you 'felgall' and 'joesimmons' for pointing out the (); at the end to invoke the function.

    I tried the:
    alert( JSON.parse(manifest) );
    suggestion, but that did not show anything
    other than "unexpected character" in the error console.
    Quote Originally Posted by joesimmons View Post
    Can you show your full code? (Pastebin, please).

    ...
    Here is what I am using with FF browser.
    Code:
    <!DOCTYPE HTML>
    <html>
    <head>
    <title> Object Definition </title>
    <meta charset="utf-8">
    
    </head>
    <body>
    <div id="debugDIV"></div>
    
    <script type="text/javascript">
    // From: www.codingforums.com/showthread.php?t=299556
    
    (function(){               // starts the function
      var manifest = {         // sets up the array-like Object "manifest"
      a:                       // sets the Object "manifest" key to "a"
        {                      // begin property list for "a"
          filename:"01.jpg",   // adds property 'filename' with value '01.jpg' to key "a"
          aphorism: "old",     // adds property 'aphorism' with value 'old' to key "a"
          dog:"spot"           // adds property 'dog' with value 'spot' to key "a"
        }                      // end property list for "a"
      }
    
      var str = '';
    /* first test of above  - works ok 
      str = manifest.a.filename+'\n';
      str += manifest.a.aphorism+'\n';
      str += manifest.a.dog;
      alert(str);
    /* */
    
    /* another test of above - also works ok */
      str = manifest.a.filename+'<br>';
      str += manifest.a.aphorism+'<br>';
      str += manifest.a.dog;
      document.getElementById('debugDIV').innerHTML = str;
    /* */
    
    /* this version does not seem to work for the "parse" part */
      str = JSON.stringify(manifest);  document.getElementById('debugDIV').innerHTML += '<p>'+str;  // this line works ok
      alert( JSON.parse(str) );  // unexpected character error on this line
    /* */
    
    })();
    
    </script>
    
    </body>
    </html>
    Error message line is in RED above.

  14. #29
    New Coder
    Join Date
    Aug 2013
    Posts
    50
    Thanks
    0
    Thanked 11 Times in 11 Posts
    I asked for Pastebin, but ok.

    Anyways... I get no errors in my error console. I created an html file and ran it directly with Firefox 23.0. It alerts an object, for me. I'm not sure what the problem could be on your end.

  15. #30
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,020
    Thanks
    75
    Thanked 4,323 Times in 4,289 Posts
    Quote Originally Posted by pratto View Post
    as far as the "array like object", i got that terminology from : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys
    Yes, but as soon as you used { instead of [ to initialize the variable, it *LOST* all its array-ness.
    Code:
    var manifest = { //sets up the array-like Object "manifest"
    All the methods available on array instances (e.g, join(), concat(), push(), etc.) are NOT available to that manifest variable.

    It's kind of funny, actually.

    If you coded:
    Code:
    var manifest = [ ];
    manifest["a"] = { a: { filename:"01.jpg", ... etc. ... } };
    then you *COULD* still do
    Code:
    manifest.push( 37 );
    But if you start that same code with
    Code:
    var manifest = {  };
    Then you will get an error from m.push( ).

    If you realize that
    Code:
    var manifest = [ ];
    var manifest = new Array();
    are equivalent and that
    Code:
    var manifest = { };
    var manifest = new Object();
    are also equivalent, you can see why: An Array is an object, so it has all the properties of any Object instance. But an Object is not an instance of an Array.

    i had seen this before :alert(manifest['a'].aphorism);
    and the brackets i had put down as related to an array. but i guess you get your choice of how to call up the value in "a" that you want ( ['a'] or .a. ).
    And you can also do any of the following:
    Code:
    manifest['a'].aphorism
    manifest.a.aphorism
    manifest['a']["aphorism"]
    manifest.a['aphorism']
    ANY level in the object notation can, instead, use the array-like notation, thus conveniently allowing the use of an expression there, instead:
    Code:
    var foo = "a";
    var bar = "aphorism";
    manifest[foo][bar];
    manifest[foo].aphorism
    manifest.a[bar]
    manifest[foo]["aph" + bar.substring(3)]
    and all other variations
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.


 
Page 2 of 3 FirstFirst 123 LastLast

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •