Javascript 如何使用'';让我们;而不是",;var";
假设我有以下代码:Javascript 如何使用'';让我们;而不是",;var";,javascript,Javascript,假设我有以下代码: if (input.length >= 3) { var filtered_school = _.filter(schools, function (school) { return _.startsWith(school.label, input); }); } this.setState({ options: filtered_school }) 我不能使用“let”,因为在范围外看不到它,所以我不能将筛选的\u sch
if (input.length >= 3) {
var filtered_school = _.filter(schools, function (school) {
return _.startsWith(school.label, input);
});
}
this.setState({ options: filtered_school })
我不能使用“let”,因为在范围外看不到它,所以我不能将筛选的\u school
分配给选项
但我听说没有理由在ES6中使用var
在这种情况下如何使用let?如果,请将其置于
之外:
let filtered_school;
if (input.length >= 3) {
filtered_school = // ...
});
let
是块作用域,这意味着如果在if
块中定义它,它将不存在于块之外,因此在这种情况下必须将其提取出来。您在要使用它的作用域中声明变量。i、 e.在if
块之外
let filtered_school;
if (input.length >= 3) {
filtered_school = _.filter(schools, function(school) {
return _.startsWith(school.label, input);
});
}
this.setState({
options: filtered_school
})
让
在ES6中创建块级作用域,您可以在外部声明它,并在您的过滤器
中分配它
let filtered_school;
if (input.length >= 3) {
filtered_school = _.filter(schools, function (school) {
return _.startsWith(school.label, input);
});
}
this.setState({ options: filtered_school })
let
是块作用域,因此如果let
位于{}
内部或逻辑块中,则只能在那里访问。要使其在示例之外易于理解,请将其置于if
语句之外
let filtered_school;
if (input.length >= 3) {
filtered_school = _.filter(schools, function (school) {
return _.startsWith(school.label, input);
});
}
如果input.length
不等于或大于3,则filtered\u school
将在this.setState
中未定义。将变量声明移动到要使用它的范围内,就像其他语言一样。JavaScript奇怪的var
语义是一个异常值,而不是标准值,它让开发人员对变量应该如何声明有了一个非常有趣的想法。