int*_*ows 1 javascript arrays loops
我有一组文件,并且只想根据检测到的屏幕宽度显示一个文件。我在尝试循环并检查数组中的当前项和下一项时遇到问题。
以下是一些要求:
viewportWidth大于或等于最大视频宽度,则选择最大视频。viewportWidth小于或等于最小视频宽度,则选择最小视频viewportWidth小于当前项目但大于下一项,则选择该视频。这是我当前的代码,但我似乎无法正确理解循环/条件部分:
const viewportWidth = 1800;
const videos = [{
url: 'video1.mp4',
width: 1920
},
{
url: 'video2.mp4',
width: 1280
},
{
url: 'video3.mp4',
width: 720
},
{
url: 'video4.mp4',
width: 560
},
{
url: 'video5.mp4',
width: 420
},
];
function getVideoUrl(viewportWidth) {
if (viewportWidth > videos[0].width) {
return videos[0].url;
}
if (viewportWidth < videos[videos.length - 1].width) {
return videos[videos.length - 1].url;
} else {
let i = 0;
while (viewportWidth < videos[i].width && viewportWidth > videos[i + 1].width) {
i++
}
return videos[i].url;
}
}
const videoUrl = getVideoUrl(viewportWidth);
console.log(videoUrl);Run Code Online (Sandbox Code Playgroud)
基于以上:
viewWidth = 1200 // should output video2.mp4
viewWidth = 2000 // should output video1.mp4
vewWidth = 300 // should output video5.mp4
Run Code Online (Sandbox Code Playgroud)
恕我直言,你的方法太复杂了:-)
只需以相反的顺序循环播放视频,一旦找到宽度大于(等于)视口宽度的视频,就返回该视频。
如果没有找到,则只需在循环之后返回第一个即可。
function getVideoUrl(viewportWidth) {
for (let i = videos.length-1; i >= 0 ; --i) {
if (videos[i].width >= viewportWidth) {
return videos[i];
}
}
return videos[0];
}
Run Code Online (Sandbox Code Playgroud)