function randomize() {
var ra = Math.floor(Math.random()*ar.length=4);
document.getElementById('es').innerHTML = ar[ra];
}
有没有办法让这段代码变得更短?原因是因为我将在其他项目和对象中大量使用此代码,并且我不能像这样在内部调用它: randomize();因为我有不同的数组。
最佳答案
function randomize() {document.getElementById('es').innerHTML = ar[Math.floor(Math.random()*ar.length)];}
但是您想在不调用函数的情况下更多地使用它:
function $(id) {
return document.getElementById(id);
}
function randomize() {
$('es').innerHTML = ar[Math.floor(Math.random()*ar.length)];
}
您可以使用 ~~
来代替 Math.floor
,以实现微观的更快差异。
如果您打算更多地使用它,这可以节省一些空间和时间。但如果只有一次,请使用第一个示例。
关于JavaScript - 缩短数学函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10857572/