凯旋899 2023-02-01 17:07 采纳率: 60%
浏览 35

为什么对象数组里有数值,但是又是空的

遇到的现象和发生背景,请写出第一个错误信息

对象有一个属性,用来存数组
通过对象的方法给该属性赋值后打印输出对象,发现有数值,但是属性又是空的,不理解是什么意思

用代码块功能插入代码,请勿粘贴截图。 不用代码块回答率下降 50%

class Position {
  #localPlace = [];
  constructor() {
    this._getLocalPlace();
  }

  _getLocalPlace() {
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(
        this._loadPosition.bind(this),
        function () {
          alert('获取位置失败');
        }
      );
    }
  }

  _loadPosition(position) {
    const lat = position.coords.latitude;
    const lng = position.coords.longitude;
    this.#localPlace = [lat, lng];

    this.whereAmI();
  }

  whereAmI() {
    // console.log(this.#localPlace);
    fetch(
      `https://geocode.xyz/${this.#localPlace[0]},${
        this.#localPlace[1]
      }?geoit=json`
    )
      .then(response => response.json())
      .then(data => {
        // console.log(data);
        console.log(`你现在在${data.country}的城市${data.city}`);
      });
  }

  test() {
    console.log(this.#localPlace);
  }
}

const p = new Position();
console.log(p);
p.test();
运行结果及详细报错内容

img

我的解答思路和尝试过的方法,不写自己思路的,回答率下降 60%

对象有一个属性,用来存数组
通过对象的方法给该属性赋值后打印输出对象,发现有数值,但是属性又是空的,不理解是什么意思

我想要达到的结果,如果你需要快速回答,请尝试 “付费悬赏”
  • 写回答

2条回答 默认 最新

  • 於黾 2023-02-01 17:22
    关注

    我都没看懂你想表达什么,什么东西有数值又是空的
    有一个属性,哪个属性,变量名是什么

    评论

报告相同问题?

问题事件

  • 创建了问题 2月1日