Register

If this is your first visit, please click the Sign Up now button to begin the process of creating your account so you can begin posting on our forums! The Sign Up process will only take up about a minute of two of your time.

Results 1 to 3 of 3
Like Tree1Likes
  • 1 Post By Ronald Roe

Thread: for/in

  1. #1
    Senior Member
    Join Date
    Apr 2016
    Posts
    717
    Member #
    53891
    Liked
    11 times

    for/in

    the following piece of code is from Mozilla

    var obj = {a: 1, b: 2, c: 3};

    for (var prop in obj) {
    console.log('obj.' + prop, '=', obj[prop]);
    }

    // Output:
    // "obj.a = 1"
    // "obj.b = 2"
    // "obj.c = 3"
    https://developer.mozilla.org/en-US/...ments/for...in

    what I'm wondering is how can prop mean both the property name and the value?

  2.  

  3. #2
    Senior Member
    Join Date
    Apr 2016
    Posts
    717
    Member #
    53891
    Liked
    11 times
    and shouldn't there be an equals sign in the first statement "var = prop in object" instead of "var prop in object"?

  4. #3
    Senior Member Ronald Roe's Avatar
    Join Date
    Mar 2011
    Location
    Oklahoma City
    Posts
    3,141
    Member #
    27197
    Liked
    959 times
    This is one of those weird ones. So, you're going to run this on an object.

    What it's basically saying is "for each property in this object, do this stuff".

    Prop isn't meaning both, what they're doing is saying the property of the object. Object properties can be accessed either with dot notation:

    obj.prop

    ... or with bracket notation:

    obj[prop]

    Both of those would return the value of the property. The difference between them is that you can't pass a variable for a property with dot notation.

    Finally, no, there shouldn't be an equal sign. This is because "in obj" is not the value of prop. Prop is the name of the property of the object being referenced for that iteration of the loop.
    busso likes this.
    Ron Roe
    Web Developer
    "If every app were designed using the same design template, oh wait...Bootstrap."


Remove Ads

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
All times are GMT -6. The time now is 08:13 AM.
Powered by vBulletin® Version 4.2.3
Copyright © 2019 vBulletin Solutions, Inc. All rights reserved.
vBulletin Skin By: PurevB.com