为什么两个相等的对象显示“不相等"?在Angular 2中 [英] Why does two equal Objects shows 'not equal" in Angular 2

查看:112
本文介绍了为什么两个相等的对象显示“不相等"?在Angular 2中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从json文件上传数组.每1.5秒检查一次文件是否有任何更改(此刻我测试一个文件没有任何更改),但是当我检查

I Upload array from json file. every 1.5 second I check if there are any changes in file (at the moment I test on one file without any changes), but when I check if

    if ( this.itemsParentArray[i] !== this.itemInArray[i] )

它总是显示不相等,并且显示console.log("不相等)

it always shows that it's not equal, and console.log (""not equal")

我是否错过了代码中的某些内容?在这里:

Did I missed something in code??Here it is:

export class HomeComponent {
itemsParentArray = [];
itemInArray = [];
myRes: Content;
showAssigned:boolean = false;

constructor(private structureRequest: StructureRequestService) {
    setInterval(() => {
        this.timerGetStructure();
    }, 1500);
}
//  using with setInterval to get new data and sets into content Array with this.updateItems(result) if it's new

timerGetStructure() {
    this.structureRequest.sendRequest().subscribe((result) => this.updateItems(result));
}
updateItems(result) {
    this.myRes =  result;
    this.itemInArray = this.myRes.content;
    for ( let i = 0; i < this.itemInArray.length; i++) {
                if ( this.itemsParentArray[i] !== this.itemInArray[i] ) {
                   // this.itemsParentArray[i] = this.itemInArray[i];
                   console.log("not equal");
                }
            }
}

//
ngOnInit() {
    //makes http request and puts result into parentArray after 3 sec.
    this.structureRequest.sendRequest().subscribe((result) => this.viewNodes(result));
}
//view items
viewNodes(result) {
    setTimeout(() => {
        this.myRes =  result;
        this.itemsParentArray = this.myRes.content;
        this.showAssigned = true;
    }, 3000);
}
}

如您所见,它从同一文件加载数据(我不更改文件数据!!):

As you see it loads data from the same file (I do not change file data!!!):

this.itemsParentArray = this.myRes.content;

和(每1.5秒):

this.itemInArray = this.myRes.content;

推荐答案

== ,尤其是 === 不会检查对象是否包含与相同的值.它只是检查它是否是相同的对象引用.

== and especially === don't check if the object contains the same properties with the same values. It just checks if it is the same object reference.

{} == {} 

{} === {}

还会导致 false .

另请参见打字稿:避免按引用进行比较 柱塞示例

这篇关于为什么两个相等的对象显示“不相等"?在Angular 2中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆