缩短一行。最多80个字符

时间:2018-12-01 03:32:27

标签: javascript

我怎样才能使这一行更短?

const otherVideos = (video) => video.getVideoUrl() !== player.getVideoUrl();

我能以某种方式将其分成两半吗?

https://jsfiddle.net/hzyrfkwb/6/

 function onPlayerStateChange(event) {
        const player = event.target;
        if (event.data === YT.PlayerState.PLAYING) {
            const otherVideos = (video) => video.getVideoUrl() !== player.getVideoUrl();
            const pauseVideo = (video) => video.pauseVideo();
            players.filter(otherVideos).forEach(pauseVideo);
        }
        const playerVars = player.b.b.playerVars;
        if (playerVars.loop && event.data === YT.PlayerState.ENDED) {
            player.seekTo(playerVars.start);
        }
    }

1 个答案:

答案 0 :(得分:3)

一个选择是仅将显式返回与{一起使用,而不是隐式返回:

const otherVideos = (video) => {
  return video.getVideoUrl() !== player.getVideoUrl();
};

或者,如果您愿意,也可以使用隐式return和(

const otherVideos = (video) => (
  video.getVideoUrl() !== player.getVideoUrl() // no semicolon
);

此外,如果player.getVideoUrl()在多次迭代中都没有变化,则可以预先将其放入变量中,然后只需访问该变量即可:

function onPlayerStateChange(event) {
  const player = event.target;
  const playerURL = player.getVideoUrl();
  if (event.data === YT.PlayerState.PLAYING) {
    const otherVideos = (video) => video.getVideoUrl() !== playerURL;
    const pauseVideo = (video) => video.pauseVideo();
    players.filter(otherVideos).forEach(pauseVideo);
  }
  const playerVars = player.b.b.playerVars;
  if (playerVars.loop && event.data === YT.PlayerState.ENDED) {
    player.seekTo(playerVars.start);
  }
}

(最长行为66个字符,外加4个缩进)

您还可以使用匿名函数,而不是将filterforEach回调放入其自己的变量中:

function onPlayerStateChange(event) {
  const player = event.target;
  const playerURL = player.getVideoUrl();
  if (event.data === YT.PlayerState.PLAYING) {
    players
      .filter(video => video.getVideoUrl() !== playerURL)
      .forEach(video => video.pauseVideo());
  }
  const playerVars = player.b.b.playerVars;
  if (playerVars.loop && event.data === YT.PlayerState.ENDED) {
    player.seekTo(playerVars.start);
  }
}

(现在,最长的一行是if (playerVars.loop...的那一行)