【问题标题】:Looping through a local storage array returns undefined循环访问本地存储数组返回未定义
【发布时间】:2021-06-10 16:46:49
【问题描述】:

上下文:我有一个从推送到本地存储的字符串条目集合创建的数组。然后我遍历这些条目并从对象数组中找到匹配的值。它应该带回匹配的对象。

问题:只有在应用程序打字稿文件中使用模拟数据时,我才能让它返回匹配的对象。但是,当我引入本地存储来替换推送值的模拟数组时,结果对象返回未定义。我无法理解的是,执行映射之前的控制台日志确实表明两个查询数组(包括本地存储的数组)已准备好并且与模拟数据一样。

我在stackblitz 上创建了一个同样显示错误的示例。我在示例中创建了两个循环。一个用于本地存储,一个用于模拟数据。

我正在使用 Angular 应用程序,因此出于演示目的,我已在构造函数中推送到本地存储,并在 ngOnInit() 中填充了数组。通常本地存储会在另一个页面上填充,但为了便于演示,这代表了具有相同结果的类似场景。

 export class AppComponent {
  constructor() {
    //passing data into local storage
    let data = ["1", "2"];
    const key = "item";
    let id = JSON.parse(localStorage.getItem(key)) || [];
    if (id.indexOf(data) == -1) {
      id.push(data);
      localStorage.setItem(key, JSON.stringify(id));
    }
  }

  array = [];
  arrayTwo = ["1", "2"];
  fieldOptions = [
    {
      id: "1",
      type: "I_am_RED",
      displayKey: "I_am_RED"
    },
    {
      id: "5",
      type: "I_am_RED",
      displayKey: "I_am_RED"
    },
    {
      id: "2",
      type: "I_am_BLUE",
      displayKey: "I_am_BLUE"
    },
    {
      id: "3",
      type: "I_am_BLUE",
      displayKey: "I_am_BLUE"
    },
    {
      id: "4",
      type: "I_am_GREEN",
      displayKey: "I_am_GREEN"
    }
  ];

  ngOnInit() {
    const key = "item";
    this.array.push(JSON.parse(localStorage.getItem(key)));

    //local storage loop
    for (const item of this.array) {
      let obj = this.fieldOptions.find(o => o.id === item);
      console.log("Array Object result getting local storage", obj);
    }

    //mock loop - mock array to simulate local storage
    for (const item of this.arrayTwo) {
      let obj = this.fieldOptions.find(o => o.id === item);
      console.log("ArrayTwo Object result", obj);
    }
  }
}

【问题讨论】:

  • [ 1, 2 ] != [ 1, 2 ] - 不要忘记 objects 总是唯一的,并且数组是一个对象。即使它包含相同的元素,它也将永远是相同的数组。您必须对对象进行更深入的比较以查看它是否匹配。此外,非现有对象的 JSON 解析错误也可能导致此问题。尝试JSON.parse( localStorage.getItem || "[]" ) 以确保您始终至少取回一个有效数组。
  • 你应该这样做:for (const item of this.array) { console.log(item) console.log(this.fieldOptions)你匹配错误的东西。使用 item[0][0]item[0][1] 你会将它与 1 或 2 匹配到 ids 或上一级 item[0] 并循环并为每个执行。
  • 似乎这是问题所在 - 我不能使用 [0] 因为该值总是会改变,例如可能是 [??] 数量。

标签: javascript angular typescript local-storage


【解决方案1】:

您正在本地存储中添加数组数组。试试下面的代码:

import { Component } from "@angular/core";
import { forEach } from "@angular/router/src/utils/collection";

@Component({
  selector: "my-app",
  templateUrl: "./app.component.html"
})
export class AppComponent {
  constructor() {
    //passing data into local storage
    let data = ["1", "2"];
    const key = "item";
    let id = JSON.parse(localStorage.getItem(key)) || [];

    for (let i = 0; i < data.length; i++) {
      if (id.indexOf(data[i]) == -1) {
        id.push(data[i]);
      }
    }
    localStorage.setItem(key, JSON.stringify(id));
  }

  array = [];
  arrayTwo = ["1", "2"];
  fieldOptions = [
    {
      id: "1",
      type: "I_am_RED",
      displayKey: "I_am_RED"
    },
    {
      id: "5",
      type: "I_am_RED",
      displayKey: "I_am_RED"
    },
    {
      id: "2",
      type: "I_am_BLUE",
      displayKey: "I_am_BLUE"
    },
    {
      id: "3",
      type: "I_am_BLUE",
      displayKey: "I_am_BLUE"
    },
    {
      id: "4",
      type: "I_am_GREEN",
      displayKey: "I_am_GREEN"
    }
  ];

  ngOnInit() {
    const key = "item";
    this.array = JSON.parse(localStorage.getItem(key));
    console.log("get storage", this.array);

    for (const item of this.array) {
      let obj = this.fieldOptions.find(o => o.id === item);
      console.log("Array Object result getting local storage", obj);
    }

    for (const item of this.arrayTwo) {
      let obj = this.fieldOptions.find(o => o.id === item);
    }
  }
}

【讨论】:

    【解决方案2】:

    在构造函数中,“data”是一个字符串数组。 indexOf() 将尝试比较对象身份,而不是内容,因此 id.indexOf(data)始终为 -1 (因为["1", "2"] == ["1", "2"] 是假的)。

    在 ngOnInit 中,您将一个数组推送到另一个数组,这实际上是您想要的吗?我猜你可能想使用this.array = this.array.concat(JSON.parse(localStorage.getItem(key)))

    【讨论】:

    • 以上是非常好的指针 - 我真的不需要 indexOf,它以前用于阻止 id 被多次推送到本地存储。问题依然存在,本地存储数据被循环后返回 undefined
    • 您仍在将一个数组合并到一个数组中,因此您最终得到了一个数组数组,这意味着您正在尝试将一个数组与单个字符串进行比较。
    猜你喜欢
    • 1970-01-01
    • 2017-09-30
    • 2020-11-16
    • 1970-01-01
    • 2018-06-03
    • 2020-07-16
    • 1970-01-01
    • 1970-01-01
    • 2020-02-18
    相关资源
    最近更新 更多