0
我在對象編程上有一個新手。我正在向Chrome控制檯記錄一個對象,並且無法注意到一個奇怪的行爲。Chrome控制檯顯示對象屬性爲undefined
某些屬性出現在日誌底部爲未定義,但對頂部的值。
當我從我的函數返回對象時,它將返回那些相同的屬性定義,因此Dirty Sock
和Microphone
被定義。那麼爲什麼控制檯認爲他們不是?
我的代碼:
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;
}, {});
}
}
值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"]
];
你傳入的'arr2'的值是多少? – Kevin
@Kevin將「arr1」和「arr2」的值添加到問題 –
看起來您的錯誤出現在名稱中。注意髮夾和保齡球有值,是陣列之間的兩個常用名稱。陣列不能隱式地在「Half-Eaten Apple」和「Dirty Sock」或「Microphone」之間建立連接 – Kevin