跳到主要内容

isEqual

2024年06月17日
柏拉文
越努力,越幸运

一、认识


问题: 请手写实现一个函数, 这个函数的功能为判断a: {x:1,y:2}b:{y:2,x:1} , 如果属性值相同, 那么返回 true

二、语法


三、实现


function isObject(value) {
return typeof value === "object" && value !== null;
}

function isEqual(value, other) {
if (!isObject(value) || !isObject(other)) {
return value === other;
}
const valueKeys = Object.keys(value);
const otherKeys = Object.keys(other);
if (valueKeys.length !== otherKeys.length) {
return false;
}
for (let key in value) {
if (!isEqual(value[key], other[key])) {
return false;
}
}
return true;
}

const value = { x: 1, y: 2, z: [{ x: 1, y: 2 }, 2, 3] };
const other = { y: 2, x: 1, z: [{ y: 2, x: 1 }, 2, 3] };
console.log(isEqual(value, other));