DEV Community

xiaoyao-yao
xiaoyao-yao

Posted on • Edited on

After obtaining the NEXT-Data data from the AppStore, the HarmonyOS NEXT-Data data is found to be the same data


I'm using

dataTime.indexOf(Time)
to find the same data in the Date[] array,
I found that even though I know exactly that there is a value of the Data property in the dataTiem that is the same as the Time,
However, it gets -1 and the comparison is false.

Analyze the cause of the error:

Reference Comparison Mechanism Date is a complex data type (object) that compares the memory address of the object rather than the actual value when compared directly in JavaScript/ArkTS using === or indexOf. For example, even if the Timestamp of the Date object obtained from AppStorage is the same as that of the original object, it may be a different instance, resulting in indexOf returning -1. In the vernacular, it is a complex data type of Date[], when comparing, it will compare whether their addresses are the same, but will not compare their values, which is essentially caused by the difference between object reference comparison and value comparison, so how do we achieve it? Compare their values to get the results we expect.

The sample code is as follows:

Method 1: Use JSON

@Entry
@Component
struct Index {
@State dataTime: Array = []
@State Time: Date = new Date()
aboutToAppear(): void {
this.dataTime.forEach((item)=>{
console.log(''+Boolean(JSON.stringify(item)===JSON.stringify(this.Time)))
})
}
build() {

}
}

Use JSON.stringify() to compare Date objects, i.e. serialized strings

Method 2: Use the original method to compare, that is, use getTime() to compare timestamps

@Entry
@Component
struct Index {
@State dataTime: Array = []
@State Time: Date = new Date()
aboutToAppear(): void {
this.dataTime.forEach((item)=>{
console.log(Boolean(item.getTime()=== this.Time.getTime())+'')
})
}
build() {

}
}

Compare timestamps (numeric types) directly to avoid referencing issues. Efficient performance without the need to convert data types.

Method 3: Storage optimization

When persisting the Date type, the timestamp (number) is stored instead of the Date object.

Save to AppStorage
AppStorage.setOrCreate('lastLogin', new Date().getTime());

Read and convert to Date
const timestamp = AppStorage.get('lastLogin');
const lastLogin = new Date(timestamp);

 Note that this only applies to simple Date objects, and may not be valid if the object contains other attributes. Performance is low, and frequent operations may affect rendering.

You can choose the right way according to your needs.

Top comments (0)