Chrome控制台将对象属性显示为未定义

时间:2017-07-27 18:54:35

标签: javascript google-chrome

我是对象编程的新手。我正在将对象记录到Chrome控制台,并且无法注意到一种奇怪的行为。

Some objects properties appear as undefined and as if they had values at the same time

某些属性在日志底部显示为未定义,但在顶部有值。

当我从函数返回对象时,它会返回定义的相同属性,因此定义了Dirty SockMicrophone。那么为什么控制台认为它们不是?

我的代码:

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;
    }, {});
  }
}

arr1arr2的值如下:

   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"]
];

1 个答案:

答案 0 :(得分:1)

console.log输出末尾的信息框(在Chrome控制台中)可能会声明刚刚重新计算了输出。如果你想在输出时知道对象的状态,我建议先创建一个字符串,然后输出。在您的示例中,请尝试:

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

然后看看会发生什么。