首页 > 解决方案 > 一个箭头函数中的两个返回语句

问题描述

考虑以下:

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?

标签: javascriptreturnarrow-functions

解决方案


Actullay 您对两种方法提出了担忧:

一个。

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

B.

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

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

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


推荐阅读