JavaScript - 缩短数学函数

JavaScript - shorten math function

本文关键字:函数 JavaScript      更新时间:2023-09-26
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);