简体   繁体   中英

JavaScript - shorten math function

function randomize() {
var ra = Math.floor(Math.random()*ar.length=4);
document.getElementById('es').innerHTML = ar[ra];
}

Is there a way to short this code even more than it is? The reason why is because I'm going to be using this code a lot in other projects and objects and I cannot just call it inside like this: randomize(); because I have diffrent arrays.

function randomize() {document.getElementById('es').innerHTML = ar[Math.floor(Math.random()*ar.length)];}

But you wanted to use it more without a function call:

function $(id) {
return document.getElementById(id);
}

function randomize() {
$('es').innerHTML = ar[Math.floor(Math.random()*ar.length)];
}

And instead of Math.floor , you can use ~~ for a microscopical faster diffrence.

This saves some space and time if you are going to use it more. But if only one time, use the first example.

Without knowing what, precisely, you're doing, I'd suggest passing the relevant arguments into the function as parameters:

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM