javascript - 一个箭头函数中的两个返回语句
问题描述
考虑以下:
class VillageState {
constructor(place, parcels) {
this.place = place;
this.parcels = parcels;
}
move(destination) {
if (!roadGraph[this.place].includes(destination)) {
return this;
} else {
let parcels = this.parcels.map(p => {
if (p.place != this.place) return p;
return {place: destination, address: p.address};
}).filter(p => p.place != p.address);
return new VillageState(destination, parcels);
}
}
}
我感兴趣的部分在这里:
let parcels = this.parcels.map(p => {
if (p.place != this.place) return p;
return {place: destination, address: p.address};
}).filter(p => p.place != p.address);
如您所见,在 this.parcels 上调用的 map 函数中有两个 return 语句。没有 else 关键字,所以我想知道它的行为方式。最初的“return p”语句是否将该值返回给它下面的表达式?它是否将其返回到原始功能?或者它是否允许每个项目有两个条件.. 例如,如果 p.place != this.place,按原样返回 p,但对于其余的,返回具有这些属性/值的对象?为什么这里省略了else?
解决方案
Actullay 您对两种方法提出了担忧:
一个。
if (condition) {
// do
// things...
}
B.
if (!condition) { return; }
// do
// things...
规则很简单:如果函数返回,它会忽略所有后续指令。
答案是它们同样有效,但通常采用 B 来提供更好的可读性,尤其是在用于避免许多嵌套条件时。
推荐阅读
- amazon-web-services - AWS:将参数从代码部署触发器传递给 Lambda
- python - 在python中根据变量类型处理数据子集
- scenekit - What is the best approach to render 3D model in iOS after facial landmark detection?
- ios - 通过 appaloosa ipa 分发,无需 udid
- javascript - Angular 4 ngIf 检查可变长度以插入条件
- ios - 如何从 XIB 文件访问 ViewController 中的 IBoutlet
- android - AndroidStudio - 发布构建失败,出现“java.exe ...创建进程错误=206 ...名称或扩展名太长”
- amazon-web-services - 名称解析暂时失败
- python - 使用 Saved xgboost Sklearn XGBClassifier Model State 预测新数据
- javascript - Onsubmit 在使用 php 的 javascript 中不起作用