简体   繁体   中英

javascript variable is not defined error when try to access the value inside the object?

  const roomAndReservationBinding = (rooms, reservations) => {
    var roomInfo = rooms;
    for (var i = 0; i <= roomInfo.length; i++) {
      var room = roomInfo[i];

      console.log(room.id);
    }
  };

// on console i get the IDs printed as expected, but on the browser i get the following error, room is undefined on the line of console.log() function

This is the root cause -:

for (var i = 0; i <= roomInfo.length; i++) {

You are iterating one extra time, it should be this -:

for (var i = 0; i < roomInfo.length; i++) {

 const roomAndReservationBinding = (rooms, reservations) => { var roomInfo = rooms; for (var i = 0; i < roomInfo.length; i++) { var room = roomInfo[i]; console.log(room.id); } }; roomAndReservationBinding([{id:1},{id:2},{id:3}],[])

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