两个相似的if条件合二为一

时间:2014-02-16 20:05:27

标签: javascript jquery performance if-statement

在Javascript函数中,我有两个结构相似的条件。我想知道你是否可以将它们组合成一个。代码来自我的随机加密安全数字/字符生成器。 这是Java脚本代码的片段:

function randomString(length, charset, allowRandomSourceFallback) {
    var i,
        result = "";

    // First we're going to try to use a built-in CSPRNG
    if (window.crypto && window.crypto.getRandomValues) {
        values = new Uint32Array(length);
        window.crypto.getRandomValues(values);

        for (i = 0; i < length; i++) {
            result += charset[values[i] % charset.length];
        }
    }
    // IE calls it msCrypto (built-in CSPRNG)
    else if (window.msCrypto && window.msCrypto.getRandomValues) {
        values = new Uint32Array(length);
        window.msCrypto.getRandomValues(values);

        for (i = 0; i < length; i++) {
            result += charset[values[i] % charset.length];
        }
    }
    // -> No built-in functionality -> use the function Math.random()
    else {
        for (i = 0; i < length; i++) {
            result += charset[Math.floor(Math.random() * charset.length)];
        }
    }
    return result;
}

2 个答案:

答案 0 :(得分:2)

为什么不检查可用的内容然后使用它:

var availableCrypto = window.crypto || window.msCrypto; // will get whatever is available

然后像这样使用它:

availableCrypto.getRandomValues(values);

你走了:

function randomString(length, charset, allowRandomSourceFallback) {
    var i,
        result = "",
        availableCrypto = window.crypto || window.msCrypto;

    // First we're going to try to use a built-in CSPRNG
    if (availableCrypto && availableCrypto.getRandomValues) {
        values = new Uint32Array(length);
        availableCrypto.getRandomValues(values);

        for (i = 0; i < length; i++) {
            result += charset[values[i] % charset.length];
        }
    }
    // -> No built-in functionality -> use the function Math.random()
    else {
        for (i = 0; i < length; i++) {
            result += charset[Math.floor(Math.random() * charset.length)];
        }
    }
    return result;
}

答案 1 :(得分:1)

而不是将它们组合在一起,只声明一个加密函数,如下面的

var crypto = null;
if (window.crypto && window.crypto.getRandomValues) {
        crypto = window.crypto;        
    }
    // IE calls it msCrypto (built-in CSPRNG)
    else if (window.msCrypto && window.msCrypto.getRandomValues) {
        crypto = window.msCrypto ;
    }

if(crypto != null){
        values = new Uint32Array(length);
        crypto.getRandomValues(values);

        for (i = 0; i < length; i++) {
            result += charset[values[i] % charset.length];
        }
}
    else {
        for (i = 0; i < length; i++) {
            result += charset[Math.floor(Math.random() * charset.length)];
        }
    }
    return result;
相关问题