[英]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.
我正在将对象记录到Chrome控制台,并且无法注意到奇怪的行为。
Some properties appear as undefined at the bottom of the log, but have value on top. 一些属性在日志的底部显示为undefined,但在顶部具有值。
When I return the object from my function it returns with those same properties defined, therefore Dirty Sock
and Microphone
are defined. 当我从函数中返回对象时,它会返回已定义的相同属性,因此会定义
Dirty Sock
和Microphone
。 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
和arr2
值如下:
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. console.log输出(在Chrome控制台中)末尾的信息框可能会指出该输出刚刚被重新计算。 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. 然后看看会发生什么。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.