4

#yyds干货盘点#JS判断两个对象是否相等

 2 years ago
source link: https://blog.51cto.com/u_11365839/5569056
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

#yyds干货盘点#JS判断两个对象是否相等

原创

尼羲 2022-08-11 21:52:10 博主文章分类:技术扯淡 ©著作权

文章标签 i++ 取对象 属性值 文章分类 JavaScript 前端开发 yyds干货盘点 阅读数160

1.首先要先有两个对象,如下举例:

var obj1 = {
name:"xx",
sex:"man",
age:18
}

var obj2 = {
name:"xxs",
sex:"man",
age:18
}

2.判断两个对象是否相等:

function isObjectValueEqual (a, b) {
//取对象a和b的属性名
var aProps = Object.getOwnPropertyNames(a);
var bProps = Object.getOwnPropertyNames(b);
//判断属性名的length是否一致
if (aProps.length != bProps.length) {
return false;
}
//循环取出属性名,再判断属性值是否一致
for (var i = 0; i < aProps.length; i++) {
var propName = aProps[i];
if (a[propName] !== b[propName]) {
return false;
}
}
return true;
}

3.做出相应的操作:

var isChange = isObjectValueEqual(obj1,obj2);
if (isChange == true){
console.log('没有修改,不需要提示是否保存');
}else {
console.log('发生修改,提示是否保存');
}
  • 收藏
  • 评论
  • 分享
  • 举报

Recommend

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK