如何使if语句不重复?

时间:2017-02-20 00:59:25

标签: javascript

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 } } 事件中使用以下if语句,因此每秒调用3-4次。虽然这种方法运行得很好,但我发现它没有吸引力,我希望得到一些提示,使它成为一个更简单的解决方案而不重复。

from installtools import setup

scripts = ['create_database.py', 'run_migrations.py']

setup("Shelob", "requirements.txt", scripts)

感谢您分享知识: - )

2 个答案:

答案 0 :(得分:3)

您可以使用开关语句,但这似乎只是计算适当的舍入值。由于似乎总是需要ajax请求,因此在“监视”逻辑之后调用它:

var percent_watched = 67;

if (percent_watched >= 100) {
  console.log('video ended');
} else {
  console.log(Math.floor(percent_watched/10) + '0% watched')
}
// Ajax Request

答案 1 :(得分:1)

您正在检查而我= =号码?你确定这是条件,当你在循环中递增i时。 (这似乎不是有效的逻辑)

怎么样:

var i = 0;
while (i <= percent_watched) {
  console.log(percent_watched + '% watched');
  i += 10;
  // Ajax Request
}