【问题标题】:How to add an index by storing an array in LocalStorage?如何通过在 LocalStorage 中存储数组来添加索引?
【发布时间】:2021-04-22 15:33:31
【问题描述】:
    const getLocation = () => {                                                   //현재 위치 값 가져오는 함수
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(success, error, option);
    } else {
        alert("위치정보를 사용할 수 있는 기기가 아닙니다.")
    }
}

function success(position) {
    let loca = localStorage.getItem("user_location");
    if (loca === null) {
        let dis = [];
        let arr = [{
            lat: position.coords.latitude,
            lon: position.coords.longitude,
            time: position.timestamp
        }];
        localStorage.setItem("user_location", JSON.stringify(arr));
        localStorage.setItem("distance", dis);
    } else {
        loca = JSON.parse(loca);
        localStorage.setItem("user_location", JSON.stringify(loca.concat(
            {
                lat: position.coords.latitude,
                lon: position.coords.longitude,
                time: position.timestamp
            })));

        setstate(loca);
        console.log(state)


    }
}

位置值每 15 秒定期检索一次并存储在本地存储中。 但是,数组中不仅存储了新的值,还存储了之前接收到的值。

For example
0: [{1}], -15 seconds
1: [{1}],
2: [{1},{1,2}], -15 seconds
3: [{1}],
4: [{1},{1,2}], 
5: [{1},{1,2},{1,2,3}] -15 seconds 
...

我希望将新检索到的值存储在新索引中。我该怎么做?

function success(position) {
        let loca = localStorage.getItem("user_location");
        if (loca === null) {

我的预测似乎是因为我在执行 if 语句之前获取了数组(loca),但我不知道如何修复它。

【问题讨论】:

    标签: javascript reactjs geolocation local-storage


    【解决方案1】:

    用你得到的值(当前值)附加现有值:

    localStorage.setItem(
      'user_location',
      JSON.stringify([
        ...JSON.parse(localStorage.getItem('user_location')),
        {
          lat: position.coords.latitude,
          lon: position.coords.longitude,
          time: position.timestamp,
        },
      ])
    );
    

    【讨论】:

    • 看来我歪曲了这个例子。对不起。我试着按照我告诉你的那样运行它,但结果是一样的。修改了示例!
    • 你的解释0: [{1}], -15 seconds 1: [{1}], 2: [{1},{1,2}], -15 seconds 3: [{1}], 4: [{1},{1,2}], 5: [{1},{1,2},{1,2,3}] -15 seconds 似乎让我很困惑。 intead 代表0、1、2 用于数组索引值
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-12
    • 1970-01-01
    • 2021-06-02
    相关资源
    最近更新 更多