Javascript 一个箭头函数中的两个返回语句
考虑以下几点:Javascript 一个箭头函数中的两个返回语句,javascript,return,arrow-functions,Javascript,Return,Arrow Functions,考虑以下几点: class VillageState { constructor(place, parcels) { this.place = place; this.parcels = parcels; } move(destination) { if (!roadGraph[this.place].includes(destination)) { return this; } else { let parcels = th
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?实际上,您对两种方法提出了担忧: A.
if (condition) {
// do
// things...
}
if (!condition) { return; }
// do
// things...
B.
if (condition) {
// do
// things...
}
if (!condition) { return; }
// do
// things...
规则很简单:如果函数返回,它将忽略后续的每条指令
答案是它们同样有效,但通常采用B来提供更好的可读性,特别是当用于避免许多嵌套条件时。没有什么特别之处:a
return
语句立即退出函数。如果您愿意,您可以在if。。。否则,如果。。。。else if…
构造。它与if(condition){return trueValue;}else{return false value;}
相同,但为1。如果if
块仅包含一行,则大括号是可选的;二,。如果if
块返回,则不需要else
(因为函数的整个剩余部分是else
)。return
语句终止函数调用。因此,如果if
的条件是true
,则使用第一条return
语句,函数调用在此结束。如果条件为false
,则使用第二个返回值。else
语句可以省略。感谢您的帮助,我现在理解了它。谢谢您,这完全有道理。我认为它们在这里是为了可读性。