[英]How to use ''let“ instead of ”var"
Let's say I have this code: 假设我有这段代码:
if (input.length >= 3) {
var filtered_school = _.filter(schools, function (school) {
return _.startsWith(school.label, input);
});
}
this.setState({ options: filtered_school })
I can't use 'let' as it can't be seen outside the scope so I can't assign filtered_school
to options
. 我不能使用'let',因为它不能在范围之外看到所以我不能将filtered_school
分配给options
。
But I hear that there is no reason to use var in ES6. 但我听说没有理由在ES6中使用var。
How can I use let in this situation? 在这种情况下如何使用let?
Just put it outside the if
: 把它放在if
之外:
let filtered_school;
if (input.length >= 3) {
filtered_school = // ...
});
let
is block-scoped, meaning if you define it within the if
block, it won't exist outside of it so you have to extract it out in this situation. let
是块范围的,这意味着如果你在if
块中定义它,它将不会存在于它之外,因此你必须在这种情况下将其解压缩。
You declare the variable in the scope you want to use it in. ie outside of the if
block. 您在要使用它的范围内声明变量。即在if
块之外。
let filtered_school;
if (input.length >= 3) {
filtered_school = _.filter(schools, function(school) {
return _.startsWith(school.label, input);
});
}
this.setState({
options: filtered_school
})
let
creates block level scope in ES6, you can declare it outside and assign it in your filter
. let
在ES6中创建块级范围,您可以在外面声明它并在filter
分配它。
let filtered_school;
if (input.length >= 3) {
filtered_school = _.filter(schools, function (school) {
return _.startsWith(school.label, input);
});
}
this.setState({ options: filtered_school })
let
is block scoped, so if let
is somewhere inside {}
, or in a logical block, it will only be accessible there. let
是块作用域,所以如果let
在{}
内部或逻辑块中,它只能在那里访问。 To make it accessibly outside of your example place it outside the if
statement. 要使其可以在示例之外访问,请将其置于if
语句之外。
let filtered_school;
if (input.length >= 3) {
filtered_school = _.filter(schools, function (school) {
return _.startsWith(school.label, input);
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.