Javascript 如何使if语句不重复?

Javascript 如何使if语句不重复?,javascript,Javascript,下面的if语句在timeupdate事件中使用,因此每秒调用3-4次。虽然这个方法工作得很好,但我觉得它不太吸引人,我想得到一些提示,使它成为一个更简单的解决方案,而不需要重复 if (percent_watched >= 100) { while (i === 10) { console.log('video ended'); i++; // Ajax Request } } else if (percent_watched

下面的if语句在
timeupdate
事件中使用,因此每秒调用3-4次。虽然这个方法工作得很好,但我觉得它不太吸引人,我想得到一些提示,使它成为一个更简单的解决方案,而不需要重复

if (percent_watched >= 100) {
    while (i === 10) {
        console.log('video ended');
        i++;
        // Ajax Request
    }
} else if (percent_watched >= 90) {
    while (i === 9) {
        console.log('90% watched');
        i++;
        // Ajax Request
    }
} else if (percent_watched >= 80) {
    while (i === 8) {
        console.log('80% watched');
        i++;
        // Ajax Request
    }
} else if (percent_watched >= 70) {
    while (i === 7) {
        console.log('70% watched');
        i++;
        // Ajax Request
    }
} else if (percent_watched >= 60) {
    while (i === 6) {
        console.log('60% watched');
        i++;
        // Ajax Request
    }
} else if (percent_watched >= 50) {
    while (i === 5) {
        console.log('50% watched');
        i++;
        // Ajax Request
    }
} else if (percent_watched >= 40) {
    while (i === 4) {
        console.log('40% watched');
        i++;
        // Ajax Request
    }
} else if (percent_watched >= 30) {
    while (i === 3) {
        console.log('30% watched');
        i++;
        // Ajax Request
    }
} else if (percent_watched >= 20) {
    while (i === 2) {
        console.log('20% watched');
        i++;
        // Ajax Request
    }
} else if (percent_watched >= 10) {
    while (i === 1) {
        console.log('10% watched');
        i++;
        // Ajax Request
    }
}

感谢您分享知识:-)

您正在检查,而我===number?你确定这就是条件吗?当你在循环中增加i时。(这似乎不符合逻辑)

那么:

var i = 0;
while (i <= percent_watched) {
  console.log(percent_watched + '% watched');
  i += 10;
  // Ajax Request
}
var i=0;
虽然(i您可以使用switch语句,但是这似乎只是一个计算适当舍入值的问题。因为ajax请求似乎总是必需的,所以在“监视”逻辑之后调用它:

var百分比=67;
如果(观看的百分比>=100){
console.log(“视频结束”);
}否则{
console.log(数学地板(监视百分比/10)+“0%监视”)
}

//Ajax请求
如果您正在收听
timeupdate
事件,难道您不能获取
currentTime
并将其除以总时间吗?EDIT没有看到Ajax请求

media.addEventListener('timeupdate', function(event) {
  console.log(media.currentTime/totalTime * 100 + '%')
  // do ajax request thing
}

你听说过switch语句吗?我从来没有使用过它,因为我对JavaScript相当陌生,但我肯定会接受这一提示来解决这个问题。你使用
while
循环肯定很奇怪。循环体最多只执行一次(因为你在体中修改
I
)。我建议阅读JavaScript教程,以更好地了解基本结构:.MDN是否是一个好的源代码,请参阅。@user45681。switch语句将与OP中显示的if语句示例一样重复和冗长。因为您仍然必须识别每个可能的条件。