API11,如何更改数组中某个字段的全部值~?

我最开始没想定义class来做假数据,我想用Record来直接造假数据,但是好像是方式不对,没造出来~

然后就是更改数组中某个字段的值,原API9中是正常执行的,但是API11中原来的方法就会报错,大家有空帮我看看应该怎么修改~感谢

class testModel {
  time: number
  value: number

  constructor(time: number, value: number) {
    this.time = time
    this.value = value
  }
}

const testData: testModel[] = [
  new testModel(1010, 1),
  new testModel(1012, 5),
  new testModel(1013, 9),
  new testModel(1014, 6),
  new testModel(1015, 2)
]

@Entry
@Component
struct CanvasIndex {
  @State LineArray: testModel[] = testData
  @State yScale: number = 1

  aboutToAppear(): void {
    let maxValue = Math.max(...this.LineArray.map(item => item.value));
    let minValue = Math.min(...this.LineArray.map(item => item.value));

    this.yScale = 300 / (maxValue - minValue) //y轴值换算的比例

    //按照比例,更新数据中的value值
    this.LineArray = this.LineArray.map(item => ({ ...item, value: (item.value - minValue) * this.yScale })); 
  }

  build() {
    Column() {
      ForEach(this.LineArray, (item: testModel) => {

        Text(item.value.toString())

      }, (item: testModel) => JSON.stringify(item))
    }
  }
}
DevEco Studio
API11
2024-07-22 14:07:30
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
Noedd
class testModel {
  time: number
  value: number

  constructor(time: number, value: number) {
    this.time = time
    this.value = value
  }
}

const testData: testModel[] = [
  new testModel(1010, 1),
  new testModel(1012, 5),
  new testModel(1013, 9),
  new testModel(1014, 6),
  new testModel(1015, 2)
]

@Entry
@Component
struct CanvasIndex {
  @State LineArray: testModel[] = testData
  @State yScale: number = 1

  aboutToAppear(): void {
    let maxValue = Math.max(...this.LineArray.map(item => item.value));
    let minValue = Math.min(...this.LineArray.map(item => item.value));

    this.yScale = 300 / (maxValue - minValue) //y轴值换算的比例

    //按照比例,更新数据中的value值
    // this.LineArray = this.LineArray.map(item => ({ ...item, value: (item.value - minValue) * this.yScale }));
    // /*方案一:生成新的testModel*/
    // this.LineArray = this.LineArray.map(item => {
    //   const newItem = new testModel(item.time, (item.value - minValue) * this.yScale);
    //   return newItem;
    // });
    /*方案二:直接修改原对象*/
    this.LineArray.forEach((item, index) => {
      this.LineArray[index].value = (item.value - minValue) * this.yScale;
    });
  }

  build() {
    Column() {
      ForEach(this.LineArray, (item: testModel) => {

        Text(item.value.toString())

      }, (item: testModel) => JSON.stringify(item))
    }
  }
}
分享
微博
QQ
微信
回复
2024-07-22 15:15:54
提问
该提问已有0人参与 ,帮助了0人