typescript 变量 'xxx' 在被赋值之前被使用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/59325106/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Variable 'xxx' is used before being assigned
提问by Sandro Rey
I have this piece of code
我有这段代码
let hostel : HostelType;
hostels.forEach( (r) => {
const i = r.identifier.findIndex((_identifier: any) => _identifier.id === '433456');
hostel = hostels[i];
});
hostel.serviceLevel.value = 'P';
but I have a compilation error:
但我有一个编译错误:
Variable 'hostel' is used before being assigned.
采纳答案by Maxim Palenov
You should be sure that there is an instance assigned:
您应该确保分配了一个实例:
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';
Ideally the code should be something like that:
理想情况下,代码应该是这样的:
const hostel = hostels.find(x => x.identifier === '433456');
It's not clear why identifier
is an array and how it's related to the index in the hostels
array.
目前尚不清楚为什么identifier
是数组以及它与hostels
数组中的索引有何关系。
回答by Royce
You are using it before being initialized.
您在初始化之前正在使用它。
You need to initialize it before the loop with something like hostel = new HostelType();
你需要在循环之前用类似的东西初始化它 hostel = new HostelType();
回答by LeGEC
You either need to initialize hostel
before using it in your hostel.serviceLevel.value = 'P';
statement,
or check if it is indeed defined :
您要么需要hostel
在hostel.serviceLevel.value = 'P';
语句中使用它之前进行初始化,
要么检查它是否确实已定义:
if (typeof hostel !== 'undefined') {
hostel.serviceLevel.value = 'P';
}
The hostel
variable may be undefined :
该hostel
变量可以是不确定的:
- if
hostels
is empty (the code inside the callback will never be called), - if the last element in
hostels
contains an identifier whoseid
field matches433456
(i
will be-1
on the last iteration)
- 如果
hostels
为空(回调中的代码永远不会被调用), - 如果中的最后一个元素
hostels
包含一个标识符,其id
字段匹配433456
(i
将-1
在最后一次迭代中)