首页 > 解决方案 > 使用间隔返回 TypeError 对数组进行洗牌不是函数

问题描述

我想每 10 秒洗一次列表。此列表是 mat-table 的数据源

  list = [
    { position: 1, name: 'player1' },
    { position: 2, name: 'player2' },
    { position: 3, name: 'player3' },
    { position: 4, name: 'player4' },
    { position: 5, name: 'player5' },
    { position: 6, name: 'player6' },
    { position: 7, name: 'player7' },
    { position: 8, name: 'player8' },
    { position: 9, name: 'player9' },
  ];

  dataSource = this.list;

我有一个随机排列数组的函数。参考:帖子

shuffleArray(array):[] {
    let currentIndex = array.length, temporaryValue, randomIndex;

    // While there remain elements to shuffle...
    while (0 !== currentIndex) {

      // Pick a remaining element...
      randomIndex = Math.floor(Math.random() * currentIndex);
      currentIndex -= 1;

      // And swap it with the current element.
      temporaryValue = array[currentIndex];
      array[currentIndex] = array[randomIndex];
      array[randomIndex] = temporaryValue;
    }

    return array;
  }

当我只是调用它时 onInit() 工作正常,并且将列表洗牌一次

  ngOnInit(): void {
    this.shuffleDatasource();
  }

  shuffleDatasource(): void {
    this.dataSource = this.shuffleArray(this.list);
  }

当我像这样在间隔调用它时,

  ngOnInit(): void {
    this.shuffleDatasource();
    setInterval(this.shuffleDatasource, 10000);
  }

我得到错误:ERROR TypeError: this.shuffleArray is not a function

你有解决这个问题的想法吗?

标签: angulartypescript

解决方案


推荐阅读