简体   繁体   中英

Chrome console shows object property as undefined

I've a newbie on object programming. I was logging an object to the Chrome console and couldn't fail to notice a weird behavior.

一些对象属性显示为未定义,并且好像它们同时具有值

Some properties appear as undefined at the bottom of the log, but have value on top.

When I return the object from my function it returns with those same properties defined, therefore Dirty Sock and Microphone are defined. So why does the console think they are not?

My code:

function updateInventory(arr1, arr2) {
  let currentInv = array2DToObject(arr1);
  let newItems = array2DToObject(arr2);
  console.log(currentInv); //This is the log I'm speaking about.

  for(let key in currentInv) {
    if(newItems.hasOwnProperty(key)) {
      currentInv[key] = currentInv[key] + newItems[key];
      delete newItems[key];
    } else {
      currentInv[key] = newItems[key];
      delete newItems[key];
    }  
  }

  if(Object.keys(newItems === 0) && newItems.constructor === Object) {
    return currentInv;
  } else {
    return 'A mistake has occured, newItems obj has not been emptied correctly';
  }

  function array2DToObject (arr) {
     return arr.reduce((acc, curr) => {
      acc[curr[1]] =  curr[0] ;
      return acc;
    }, {});
  }
}

Values for arr1 and arr2 are as follow:

   arr1 = [
    [21, "Bowling Ball"],
    [2, "Dirty Sock"],
    [1, "Hair Pin"],
    [5, "Microphone"]
];

 arr2 = [
    [2, "Hair Pin"],
    [3, "Half-Eaten Apple"],
    [67, "Bowling Ball"],
    [7, "Toothpaste"]
];

The information box at the end of your console.log output (in the Chrome console) is likely to state that the output has just been recalculated. If you want to know the state of your objects at the time of outputting, I would suggest creating a string first and then outputting. In your example, try:

console.log(JSON.stringify(currentInv));

And then see what happens.

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