数据处理的一个问题

Cc_loveCx
• 31

var obj = {
name:'ss',
age:12,
arr:[1,2]
}

var obj1={
name:'aa',
age:'12',
arr:[0,1]
}

obj 和 obj1对比 name属性值不相同
age 的值为 12 和 ’12‘ 用 == 判断 也是相同的 不用处理

2个回答
✓ 已被采纳
``````/**
* @param {unknown} m
* @param {unknown} n
* @return {Array<number | string | symbol>}
*/
const diff = (function () {
const IDENTITY_TYPES = [
["number", "string"],
];

/**
* @param {unknown} m
* @param {unknown} n
* @return {boolean}
*/
function isDiff (m, n) {
return !isIdentityType(m, n) ||
(
isPrimitive(m)
? m != n
: isDiffObject(m, n)
);
}

/**
* @param {unknown} m
* @param {unknown} n
* @return {boolean}
*/
function isDiffObject (m, n) {
const mKeys = Reflect.ownKeys(m);
const nKeys = Reflect.ownKeys(n);

return mKeys.length !== nKeys.length ||
Array
.from(new Set([...mKeys, ...nKeys]))
.some(key => isDiff(m[key], n[key]));
}

/**
* @param {unknown} m
* @param {unknown} n
* @return {boolean}
*/
function isIdentityType (m, n) {
const mType = typeof m, nType = typeof n;
return mType === nType ||
IDENTITY_TYPES.some(
types => types.includes(mType) && types.includes(nType),
);
}

/**
* @param {unknown} t
* @return {boolean}
*/
function isPrimitive (t) {
return "object" !== typeof t;
}

return function diff (m, n) {
if (isPrimitive(m) || isPrimitive(n)) {
throw new TypeError("diff called on non-object");
}

const diffKeys = [];

const keys = new Set([...Reflect.ownKeys(m), ...Reflect.ownKeys(n)]);
for (const key of keys) {
if (isDiff(m[key], n[key])) {
diffKeys.push(key);
}
}

return diffKeys;
};
})();``````

1. 对象属性列表获取(已知2个对象有同样的属性)
2. 对象属性值的比较

``````var CompObj=function(Obj1,Obj2){
let rtArr=[];

for(var i in Obj1) {
let tmp1=Obj1[i];
let tmp2=Obj2[i];
//下面的代码把所有情况转换为string
if(tmp1 instanceof Array){
tmp1=tmp1.sort();
tmp2=tmp2.sort();
tmp1=tmp1.join(',');
tmp2=tmp2.join(',');
}else{
tmp1=' '+tmp1;
tmp2=' '+tmp2;
}
if(tmp1!==tmp2){
rtArr.push(i);
}
}
return rtArr
}``````
撰写回答
你尚未登录，登录后可以
• 和开发者交流问题的细节
• 关注并接收问题和回答的更新提醒
• 参与内容的编辑和改进，让解决方法与时俱进