[英]JavaScript - shorten math function
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
,你可以使用~~
來實現更快的微觀差異。
如果您打算更多地使用它,這可以節省一些空間和時間。 但如果只有一次,請使用第一個例子。
在不知道你正在做什么的情況下,我建議將相關的參數作為參數傳遞給函數:
function randomize(el, array){
if (!el || !array){
return false;
}
else {
var ra = Math.floor(Math.random() * array.length=4);
// please note that I don't understand what's happening in the above line
// and suspect, quite strongly, that the '=4' was a typo. Correct as necessary
el.innerHTML = ar[ra];
}
}
// call:
randomize(document.getElementById('es'), ['1','2']);
/* or:
var el = document.getElementById('es'),
array = ['one','two'];
randomize(el,array);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.