3 回答

TA貢獻1802條經驗 獲得超5個贊
你得到true,因為你return true 在你的for循環,只要從一個對象的關鍵值等于鍵值對另一個對象。因此,當您的代碼看到該here屬性時,它將return true停止您的函數運行任何進一步的代碼。
您需要刪除此檢查,并且僅return false在您的 for 循環中,這樣您的 for 循環只會在它永不返回時完成(即:所有鍵值對都相等)。
此外,for..in循環將遍歷對象中的鍵,因此,無需將對象的鍵(使用Object.keys)放入數組中(因為這樣您將遍歷數組的鍵(即:索引))。
但是,話雖如此,您可以Object.keys用來幫助解決另一個問題。您可以使用它來獲取兩個對象中的屬性數量,因為您知道如果兩個對象中的屬性數量不同,則它們是不相同的
請參閱下面的示例:
const object1 = {
here: 1,
object: 3
};
const obj = {
here: 1,
object: 3
};
function comp(a, b) {
if (typeof a == typeof b) {
if(Object.keys(a).length !== Object.keys(b).length) {
return false; // return false (stop fruther code execution)
}
for (let key in a) { // loop through the properties of larger object (here I've chosen 'a') - no need for Object.keys
if (a[key] != b[key])
return false; // return false (stops any further code executing)
}
return true; // we only reach this point if the for loop never returned false
}
return false; // we reach this point when the two types don't match, and so we can say they're not equal
}
console.log(comp(obj, object1))

TA貢獻1798條經驗 獲得超3個贊
你得到true,因為你return true 在你的for循環,只要從一個對象的關鍵值等于鍵值對另一個對象。因此,當您的代碼看到該here屬性時,它將return true停止您的函數運行任何進一步的代碼。
您需要刪除此檢查,并且僅return false在您的 for 循環中,這樣您的 for 循環只會在它永不返回時完成(即:所有鍵值對都相等)。
此外,for..in循環將遍歷對象中的鍵,因此,無需將對象的鍵(使用Object.keys)放入數組中(因為這樣您將遍歷數組的鍵(即:索引))。
但是,話雖如此,您可以Object.keys用來幫助解決另一個問題。您可以使用它來獲取兩個對象中的屬性數量,因為您知道如果兩個對象中的屬性數量不同,則它們是不相同的
請參閱下面的示例:
const object1 = {
here: 1,
object: 3
};
const obj = {
here: 1,
object: 3
};
function comp(a, b) {
if (typeof a == typeof b) {
if(Object.keys(a).length !== Object.keys(b).length) {
return false; // return false (stop fruther code execution)
}
for (let key in a) { // loop through the properties of larger object (here I've chosen 'a') - no need for Object.keys
if (a[key] != b[key])
return false; // return false (stops any further code executing)
}
return true; // we only reach this point if the for loop never returned false
}
return false; // we reach this point when the two types don't match, and so we can say they're not equal
}
console.log(comp(obj, object1))

TA貢獻1779條經驗 獲得超6個贊
您應該使用for..of
(或只是一個普通的 old for
)而不是for..in
僅用于對象。您現在正在閱讀數組索引,而不是實際的鍵名。Object.keys
返回一個Array
of 鍵名,而不是一個Object
。
也不要早回來;現在,您在第一次鑰匙檢查后立即返回。
添加回答
舉報