如何使声明不重复?
问题描述:
以下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
}
}
感谢您的分享知识:-)
答
要检查,而我===号?你确定这是条件,当你在循环中增加我。 (这似乎是有效的逻辑并不)
怎么样:
var i = 0;
while (i <= percent_watched) {
console.log(percent_watched + '% watched');
i += 10;
// Ajax Request
}
答
你可以使用一个开关声明,然而,这似乎只是一个计算适当的四舍五入值的问题。由于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
答
如果您正在收听的timeupdate
事件,你就不能得到currentTime
然后除以总时间? EDIT没有看到ajax请求。
media.addEventListener('timeupdate', function(event) {
console.log(media.currentTime/totalTime * 100 + '%')
// do ajax request thing
}
您是否听说过switch语句? – user45681
我从来没有使用过它,因为我对JavaScript相当陌生,但我一定会采取这种解决方案。 –
你使用'while'循环肯定是奇怪的。循环体总是最多执行一次(因为你正在修改体内的“i”)。我建议阅读JavaScript教程以更好地理解基本构造:http://eloquentjavascript.net/02_program_structure.html。 –