繁体   English   中英

JavaScript - 缩短数学函数

[英]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.

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