简体   繁体   English

JavaScript - 缩短数学函数

[英]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(); 原因是因为我将在其他项目和对象中使用这些代码,我不能像这样调用它: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. 而不是Math.floor ,你可以使用~~来实现更快的微观差异。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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