gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 20:00:01 25 4
gpt4 key购买 nike

在 Javascript 函数中,我有两个结构相似的条件。我想知道你是否可以将它们合二为一。该代码来 self 的随机加密安全数字/字符生成器。以下是 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;
}

最佳答案

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

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

关于javascript - 两个相似的 if 条件合二为一,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21815847/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com