Return语句在javascript switch语句中似乎不起作用

时间:2019-11-12 03:02:32

标签: javascript foreach switch-statement return

背景:我们需要编写一个名为whereCanIPark()的函数,该函数返回车辆可用停车位的坐标,如果没有可用停车位,则返回false。我们的函数会接收一个代表停车位的数组,并接收正在寻找停车位的车辆类型的字符串。

有三种可能的车辆:普通车,小型车和摩托车。普通汽车只能停在R点。小型车可以停在R或S点。摩托车可以停在R,S或M点。在停车位阵列中,以大写和小写形式写入停车位。大写字母表示该特定位置可用,而小写字母表示该位置不可用。

我们的函数必须返回一个数组,其点的坐标为[X,Y]对。请参见下面的示例输入和输出以获取说明。

注意:特定车辆可能有多个可用位置。只要功能可用,功能选择哪个位置都没有关系。如果没有可用的位置,请记住返回false。

Input:

    const spots = [
      // COLUMNS ARE X
      //    0    1    2    3    4    5
          ['s', 's', 's', 'S', 'R', 'M'], // 0 ROWS ARE Y
          ['s', 'M', 's', 'S', 'R', 'M'], // 1
          ['s', 'M', 's', 'S', 'R', 'm'], // 2
          ['S', 'r', 's', 'm', 'R', 'M'], // 3
          ['S', 'r', 's', 'm', 'R', 'M'], // 4
          ['S', 'r', 'S', 'M', 'M', 'S'], // 5
      ]

      const vehicle = 'regular' // possible options are 'regular', 'small', or 'motorcycle'

Output:
[4, 0]

我的尝试返回未定义。

const whereCanIPark = (spots, vehicle) => {
spots.forEach((current,index)=> {
  current.forEach((current1,index1)=> {
  switch (current1){
  case "R": return vehicle == "regular" || vehicle == "small" || vehicle == "motorcycle"? [index1,index]: false
  case "S": return vehicle == "small" || vehicle == "motorcycle" ? [index1,index]: false
  case "M": return vehicle == "motorcycle" ? [index1,index]: false
  }
  })
})
}

1 个答案:

答案 0 :(得分:0)

实际上forforEach循环不会返回任何内容。

您可以阅读此blog

还有StackOverflow

中的这个问题