一个箭头函数中的两个 return 语句

Two return statements in one arrow function

考虑以下几点:

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'语句return那个值给下面的表达式吗?难道return它到原来的功能?或者它是否允许每个项目有两个条件.. 如 if p.place != this.place, return p 原样,但对于其余部分,return 一个对象这些properties/values?为什么这里省略了else?

实际上,您对两种方法表示担忧:

A.

if (condition) {
   // do
   // things...
}

B.

if (!condition) { return; }
// do
// things...

规则很简单:如果函数 returns,它会忽略所有后续指令。

答案是它们同样有效,但通常采用 B 以提供更好的可读性,尤其是在用于避免许多嵌套条件时。