【问题标题】:Variable 'xxx' is used before being assigned变量 'xxx' 在被赋值之前被使用
【发布时间】:2019-12-13 15:03:33
【问题描述】:

我有这段代码

  let hostel : HostelType;

              hostels.forEach( (r) => {
                  const i =  r.identifier.findIndex((_identifier: any) => _identifier.id === '433456');
                  hostel = hostels[i];
              });

              hostel.serviceLevel.value = 'P';

但我有一个编译错误:

 Variable 'hostel' is used before being assigned.

【问题讨论】:

  • 你的可变宿舍没有任何价值
  • 您将hostel 声明为HostelType 类型,但您没有对其进行初始化。因此,如果 forEach 没有价值,那么 hostel = hostels[i] 将不会完成。所以你然后尝试访问一个空对象的serviceLevel

标签: javascript node.js typescript


【解决方案1】:

您应该确保分配了一个实例:

let hostel : HostelType;

hostels.forEach( (r) => {
  const i =  r.identifier.findIndex((_identifier: any) => _identifier.id === '433456');

  if (i === -1 || !hostels[i]) {
    throw new Exception('There is no hostel');
  }

  hostel = hostels[i];
});

hostel.serviceLevel.value = 'P';

理想情况下,代码应该是这样的:

const hostel = hostels.find(x => x.identifier === '433456');

尚不清楚为什么identifier 是一个数组,以及它与hostels 数组中的索引有何关系。

【讨论】:

    【解决方案2】:

    在初始化之前你正在使用它。

    你需要在循环之前用hostel = new HostelType();之类的东西初始化它

    【讨论】:

      【解决方案3】:

      您需要先初始化hostel,然后才能在hostel.serviceLevel.value = 'P'; 语句中使用它,
      或检查它是否确实已定义:

      if (typeof hostel !== 'undefined') {
          hostel.serviceLevel.value = 'P';
      }
      

      hostel 变量可能未定义:

      • 如果hostels为空(回调中的代码永远不会被调用),
      • 如果hostels 中的最后一个元素包含一个标识符,其id 字段与433456 匹配(i 在最后一次迭代中将是-1

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-07-06
        • 2020-11-13
        • 1970-01-01
        • 2014-06-08
        • 2019-01-16
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多