javascript - 教程中这个函数中的 if-else 语句有何意义?

标签 javascript vue.js

我正在浏览this tutorial使用 Vue 制作一个简单的播放列表。

我对作者的 play() 函数感到困惑,尤其是一系列 if-else 语句。它似乎检查 index 是否是一个数字,如果是(我无法想象它不会如何),它似乎会跳过检查是否为数字的其余代码所选轨道与当前轨道相同,等等 (link to the repo and function in question here) :

play (index) {
  let selectedTrackIndex = this.playlist.findIndex(track => track === this.selectedTrack)

  if (typeof index === 'number') {
    index = index

  } else if (this.selectedTrack) {
    if (this.selectedTrack != this.currentTrack) {
      this.stop()
    }
    index = selectedTrackIndex
  } else {
    index = this.index
  }

  let track = this.playlist[index].howl

  if (track.playing()) {
    return
  } else {
    track.play()
  }

  this.selectedTrack = this.playlist[index]
  this.playing = true
  this.index = index
}

作者对上述代码的总结:

The method takes an index as the parameter, which specifies the track to be played. First, we get the index of the selected track. Then, we make some checks to determine the value of the index. If an index is provided as an argument and it's a number, then we use it. If a track is selected, we use the index of the selected track. If the selected track is different from the current one, we use the stop() method to stop the current one. Finally, if neither an index argument is passed nor a track is selected, we use the value of the index data property.

我检查了 MDN 和其他一些来源,没有发现 JavaScript 中 if() 后跟 else if() 有何特别之处。所以我想我一定在这里遗漏了一些东西。为什么对 index 的验证检查与检查所选轨道是否与当前轨道相同有关? else if()else block 内的其他检查似乎是您不想遗漏的内容,但他的应用程序现场演示仍然有效。我要求作者在文章的评论中详细说明,但这篇文章已经快一年了,所以我不确定他是否会回复我。提前感谢大家。

最佳答案

这并不是真正的验证测试,它只是检测是否提供了参数。如果未提供参数,或者它不是数字,则该函数将执行默认行为。

如果调用者使用 track.play(2),他们会明确告诉它播放轨道 2。测试 if (typeof index == 'number') 将成功,我们将使用给定的索引。

如果调用者使用track.play()index将为undefined,它不是一个数字,因此测试将失败,然后我们将继续进行 else if 测试。如果有选定的轨道,我们将使用它(如果当前轨道不同,则首先停止当前轨道)。

如果没有选定的轨道,我们将进入最后的 else 子句,该子句使用当前对象的 index 属性。

关于javascript - 教程中这个函数中的 if-else 语句有何意义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56401099/

相关文章:

javascript - 如何在从下拉列表中选择选项时显示确认弹出窗口

javascript - 固定位置显示在某些部分但隐藏在家里

javascript - 使用 for 循环创建动态 DOM 元素

javascript - 引用 vue.js 数据但没有

php - Laravel & VueJS 变量定义

javascript - Vue,Observable 上的过滤器属性

vue.js - VueJS 进程显示未定义

javascript - 如何在路由参数中使用斜杠

javascript - 移除悬停时的工具提示

javascript - v-绑定(bind) :checked not working in all component instances