简体   繁体   中英

looping through an array of objects

I am looping through in an array of objects and wondering why the second objects is chosen in this instance? I am learning javascript and I know this is probably really simple, I just can't figure it out.

js:

(function () {
    var students = [{
        name: "Walker",
        address: {
            street: "123 South Drive",
            city: 'Sarasota',
            state: 'FL'
        },
        gpa: [3.0, 3.4, 3.8]
    }, {
        name: "Christian",
        address: {
            street: "5601 Pebble Beach Ln",
            city: 'Sacromento',
            state: 'CA'
        },
        gpa: [2.5, 3.6, 3.8]
    }];
    console.log(students);
    var domElement = function (inner, address) {
        var name = document.getElementById('name');
        var add = document.getElementById('address');
        name.innerHTML = inner;
        add.innerHTML = address;
    };;
    for (i = 0; i < students.length; i++) {
        //console.log(students[i].name);
        domElement("name: " + students[i].name, students[i].address.city + ' ' + students[i].address.state);
    }
})();

html:

<div id="form_box">
<div id="contact-form">
    <p class="heading">Display Students Information Below:</p>
    <div id="form-box">                     

            <div id="output">
                <div id="name">
                    <p>Hello</p>
                </div>
                <div id="address">
                    <p></p>
                </div>
                <div id="gpa">
                    <p></p>
                </div>
                <div id="date">
                    <p></p>
                </div>
                <div id="gpaavg">
                    <p></p>
                </div>
                <div id="phone">
                    <p></p>
                </div>
                <!-- <div class="clear"></div> -->
            </div>

            <div id="info_box">
                <div id="info_btn">
                    <h4 id="round" class="heading">Click To See Next Student</h4>
                    <a id="button" href="#" class="buttonred">Next</a>
                </div>
            </div>
    </div>        
    <div class="clear"></div>
</div>
</div>

<script src="js/main.js"></script>

I'm probably just not seeing something (maybe in main.js) but I don't see any kind of click handler.

All I see is a loop that will change the contents of the various divs to the values defined in the structures within the arrays. Basically, from what I see on a casual glance is that the loop will execute and the divs will be filled with the last student in the array when the loop is done.

For a brief moment (too fast to see) the divs will be filled with the data from the first but it is quickly overwritten by the second.

Edit: after looking at it more I'm certain that my explanation is what is happening.

I set up a jsfiddle that shows you what is happening, a little bit, if you open your developer console.. http://jsfiddle.net/deajH/

I just commented out your console.log so you could see it execute:

for (i = 0; i < students.length; i++) {
    console.log(students[i].name);
    domElement("name: " + students[i].name, students[i].address.city + ' ' + students[i].address.state);
}

You'll see the two names both go to the console (just as your loop is designed).


You will need a function to act as the click handler on your "show next" option. You can keep an attribute on the link that tracks the index you are currently at and then just increment that value each time the link is clicked.

You can fire off the function the click handler calls, when the page finishes loading, to initialize the fields with the data from the first student.

It's not a single object that is used, all objects are used. The data from each object will be put in the elements, and for each object that will overwrite the data from the previous object.

Instead of looping through all objects, keep track of which one you want to use. Show the first initially, and change to the next when the button is clicked.

(function () {

  var students = [{
    name: "Walker",
    address: {
        street: "123 South Drive",
        city: 'Sarasota',
        state: 'FL'
    },
    gpa: [3.0, 3.4, 3.8]
  }, {
    name: "Christian",
    address: {
        street: "5601 Pebble Beach Ln",
        city: 'Sacromento',
        state: 'CA'
    },
    gpa: [2.5, 3.6, 3.8]
  }];

  function domElement (inner, address) {
    var name = document.getElementById('name');
    var add = document.getElementById('address');
    name.innerHTML = inner;
    add.innerHTML = address;
  };

  function showStudent(i) {
    domElement("name: " + students[i].name, students[i].address.city + ' ' + students[i].address.state);
  }

  var i = 0;
  showStudent(i);
  i = (i + 1) % students.Length;

  $('#button').click(function(){
    showStudent(i);
    i = (i + 1) % students.Length;
  });

})();

DEMO

I cannot see any click handler in your code, and the for loop will really to that loop, and you'll logically see the last iteration.

Try with:

(function () {

    var students = [{
        name: "Walker",
        address: {
            street: "123 South Drive",
            city: 'Sarasota',
            state: 'FL'
        },
        gpa: [3.0, 3.4, 3.8]
    }, {
        name: "Christian",
        address: {
            street: "5601 Pebble Beach Ln",
            city: 'Sacromento',
            state: 'CA'
        },
        gpa: [2.5, 3.6, 3.8]
    }];

    var c = 0;
    function getStudentData(ev) {
        ev.preventDefault();
        document.getElementById('name').innerHTML = students[c].name;
        document.getElementById('address').innerHTML = students[c].address.city+' '+
                                                       students[c].address.state;
        c = ++c%students.length;       
    }

    var btn = document.getElementById('button');
    btn.addEventListener('click', getStudentData, false);

})(); 

I think it chooses both but the second overrides the first one right after the first one puts its content. To display just the first one instead of the for put

if you want to display the first one you can remove the for and just insert the value of students[0]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM