问题:参数没有改变再次提交接口会判定为重复提交,那在前端就做限制,如果参数没改,就不往后端提交数据
解决问题就要两步走:先拷贝对象,再对比对象差异
1.拷贝对象
Object.assign()是浅拷贝,用JSON.stringify()以及JSON.parse()最方便做深拷贝了。
let _tmp = JSON.stringify(obj);//将对象转换为json字符串形式
let result = JSON.parse(_tmp);//将转换而来的字符串转换为原生js对象
注意:使用JSON.stringify()以及JSON.parse()它是不可以拷贝 undefined , function, RegExp 等等类型的
显然在我们项目里不合适,那就用 for in来实现吧
function deepCopy(obj) {
let o = {}
for(let key in obj) {
o[key] = obj[key]
}
return o
}
let obj = {
a:1,
b: undefined,
c:function() {},
d:{name:1,id:2}
}
console.log(deepCopy(obj))
2.对象对比差异
function deepCompare(x, y) {
var i, l, leftChain, rightChain;
function compare2Objects(x, y) {
var p;
if (isNaN(x) && isNaN(y) && typeof x === 'number' && typeof y === 'number') {
return true;
}
if (x === y) {
return true;
}
if ((typeof x === 'function' && typeof y === 'function') ||
(x instanceof Date && y instanceof Date) ||
(x instanceof RegExp && y instanceof RegExp) ||
(x instanceof String && y instanceof String) ||
(x instanceof Number && y instanceof Number)) {
return x.toString() === y.toString();
}
if (!(x instanceof Object && y instanceof Object)) {
return false;
}
if (x.isPrototypeOf(y) || y.isPrototypeOf(x)) {
return false;
}
if (x.constructor !== y.constructor) {
return false;
}
if (x.prototype !== y.prototype) {
return false;
}
if (leftChain.indexOf(x) > -1 || rightChain.indexOf(y) > -1) {
return false;
}
for (p in y) {
if (y.hasOwnProperty(p) !== x.hasOwnProperty(p)) {
return false;
} else if (typeof y[p] !== typeof x[p]) {
return false;
}
}
for (p in x) {
if (y.hasOwnProperty(p) !== x.hasOwnProperty(p)) {
return false;
} else if (typeof y[p] !== typeof x[p]) {
return false;
}
switch (typeof(x[p])) {
case 'object':
case 'function':
leftChain.push(x);
rightChain.push(y);
if (!compare2Objects(x[p], y[p])) {
return false;
}
leftChain.pop();
rightChain.pop();
break;
default:
if (x[p] !== y[p]) {
return false;
}
break;
}
}
return true;
}
if (arguments.length < 1) {
return true;
}
for (i = 1, l = arguments.length; i < l; i++) {
leftChain = [];
rightChain = [];
if (!compare2Objects(arguments[0], arguments[i])) {
return false;
}
}
return true;
}
测试一下吧
var obj1 = {id:1,name:"张三"}
var obj2 = {id:2,name:"李四"}
deepCompare(obj1, obj2)
image.png