let currentIndex:number = 0 let imageArr:string[] = [] let titleStr = (currentIndex + 1) + '/' + imageArr.length
let jsonStr = '{"currentIndex" : "2", "totalCount" : 4}';
// json字符串转Record对象
let data0: Record<number, string> = JSON.parse(jsonStr) as Record<number, string>;
let currentIndex: number = data0['currentIndex'];
if (currentIndex === 2) {
console.info('The type of currentIndex is number');
} else {
console.info('The type of currentIndex is not number');
} [(100000:100000:scope)] Swiper FireUnselectedEvent id:915, index:1 [(100000:100000:scope)] Swiper FireUnselectedEvent id:915, index:2 [(100000:100000:scope)] Swiper FireUnselectedEvent id:915, index:3
JSON.parse解析并不会修改目标字符串的数据类型为解析指定的数据类型,"currentIndex"解析前是string类型,使用JSON.parse解析后仍然是string类型。需要使用强制类型转换Number()后再赋值。
@Entry
@Component
struct StringChange {
@State message: string = 'Hello World';
aboutToAppear(): void {
let jsonStr = '{"currentIndex" : "2", "totalCount" : 4}';
// json字符串转Record对象
let data0: Record<number, string> = JSON.parse(jsonStr) as Record<number, string>;
let currentIndex: number = Number(data0['currentIndex']);
if (currentIndex === 2) {
console.info('The type of currentIndex is number');
} else {
console.info('The type of currentIndex is not number');
}
}
build() {
RelativeContainer() {
Text(this.message)
.id('Index1HelloWorld')
.fontSize($r('app.float.page_text_font_size'))
.fontWeight(FontWeight.Bold)
.alignRules({
center: { anchor: '__container__', align: VerticalAlign.Center },
middle: { anchor: '__container__', align: HorizontalAlign.Center }
})
.onClick(() => {
this.message = 'Welcome';
})
}
.height('100%')
.width('100%')
}
}