这是我的代码。我知道这并不完全严格,但是请阐明为什么let ... in在这里无法正常工作。
const object1 = {here: 1, object: 3};
const obj = {here: 1, object: 2};
function comp(a, b) {
if (typeof a == typeof b) {
let arra = Object.keys(a);
let arrb = Object.keys(b);
for (let key in arra){
if (a[key] == b[key]) return true
}
return false
}
}
console.log(comp(obj, object1))Run Code Online (Sandbox Code Playgroud)
以上打印,true但应该打印false
你得到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))Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
99 次 |
| 最近记录: |