echarts 随机选中地图区域

reSelectMapRandomArea() {
      const length = 9;
      this.$nextTick(() => {
        try {
          const map = this.$refs.centerLeft2ChartRef.chart;
          let index = Math.floor(Math.random() * length);
          while (index === this.preSelectMapIndex || index >= length) {
            index = Math.floor(Math.random() * length);
          }
          map.dispatchAction({
            type: "mapUnSelect",
            seriesIndex: 0,
            dataIndex: this.preSelectMapIndex,
          });
          map.dispatchAction({
            type: "showTip",
            seriesIndex: 0,
            dataIndex: index,
          });
          map.dispatchAction({
            type: "mapSelect",
            seriesIndex: 0,
            dataIndex: index,
          });
          this.preSelectMapIndex = index;
        } catch (error) {
          console.log(error);
        }
      });
    },

这段代码的思路是怎样的

阅读 2.2k
1 个回答

总长度length为9,使用Math.floor(Math.random() * length)选出0-8之间的一个整数,作为新的选中区域

preSelectMapIndex应该是上一次选中的区域下标,所以要保证index不能和preSelectMapIndex一样,就是要变化,所以用while重复去生成index(生成0-8的整数,且和preSelectMapIndex不一样)

然后先mapUnSelect取消上次的选择,再使用index设置这次的选择,最后把index赋值给preSelectMapIndex,供下次在进入这里判断使用

已参与了 SegmentFault 思否社区 10 周年「问答」打卡 ,欢迎正在阅读的你也加入。
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题