Javascript 函数/对象';s缩短代码
我想缩短一些代码,这些代码有不同的方法来替换我设置的特定模式。基本上,这段代码取代了我设置的HTML:Javascript 函数/对象';s缩短代码,javascript,jquery,Javascript,Jquery,我想缩短一些代码,这些代码有不同的方法来替换我设置的特定模式。基本上,这段代码取代了我设置的HTML:0000-AAAA-0000-BBBB 如你所见,我有3个相同的脚本。但是我就是不知道怎么做。我的目标是能够更改这些值:str.replace(/[A]/g,,A=alphSet/numSet/alphNumSet,并且可以添加:.toUpperCase(); 最后的问题是,如果我将其作为函数,我不知道如何返回这些值。如果有任何建议或想法,我将非常感谢。您已经迈出了第一步,并确定了代码的重复部分
0000-AAAA-0000-BBBB
如你所见,我有3个相同的脚本。但是我就是不知道怎么做。我的目标是能够更改这些值:str.replace(/[A]/g,
,A=alphSet/numSet/alphNumSet
,并且可以添加:.toUpperCase();
最后的问题是,如果我将其作为函数,我不知道如何返回这些值。如果有任何建议或想法,我将非常感谢。您已经迈出了第一步,并确定了代码的重复部分。现在您所要做的就是使用这些部分作为参数创建函数
function replaceWithRandom(text, regex, randomSet) {
return text.replace(regex, function() {
return randomSet[randomised(randomSet.length)].toUpperCase();
});
}
str = replaceWithRandom(str, /0/g, numSet);
str = replaceWithRandom(str, /A/g, alphSet);
str = replaceWithRandom(str, /B/g, alphNumSet);
numSet
只包含字符串,因此调用toUpperCase
是多余的,但不会引起任何问题。这里有几个地方可以删减fat。首先,我将继续将所有alphSet大写,这样您就不必调用toUpperCase().alphNumSet由2个字符串组成,您可以使用字符串连接来组合它们,而不是使用concat函数。您要查找的函数只是将发送的调用之间的差异分解出来
function randomised(len) {
return Math.floor(Math.random() * len);
}
function getRandom(str, regEx, set){
return str.replace(regEx, function() {
return set[randomised(set.length)];
});
}
function randomiseStrings(str){
var alphSet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var numSet = "0123456789";
var alphNumSet = alphSet + numSet;
str = getRandom(str, /0/g, numSet);
str = getRandom(str, /A/g, alphNumSet)
str = getRandom(str, /B/g, alphSet)
return str;
}
$('.combination').text(function(i,t){
return randomiseStrings(t);
});
提示
/[0]/=/0/
和/[A]/=/A/
等。您不需要仅为一个字符设置字符集。您可以使用返回numSet[随机(numSet.length)];
而不是创建一个变量。还要定义str
一次,而不是三次。除非您要添加更多类似的函数,否则我会保持现在的状态。使用泛型函数的替代解决方案不会像现在这样清晰。@Christphe,我正在尝试使它更“可伸缩”编写脚本只是为了学习不同的技术。因此,可以选择制作自定义模式,例如序列代码的第3行,只有数字0-2和字母A、B、C。例如0000-0000-0A2C。我只是觉得学习如何做有些有趣。
function randomised(len) {
return Math.floor(Math.random() * len);
}
function getRandom(str, regEx, set){
return str.replace(regEx, function() {
return set[randomised(set.length)];
});
}
function randomiseStrings(str){
var alphSet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var numSet = "0123456789";
var alphNumSet = alphSet + numSet;
str = getRandom(str, /0/g, numSet);
str = getRandom(str, /A/g, alphNumSet)
str = getRandom(str, /B/g, alphSet)
return str;
}
$('.combination').text(function(i,t){
return randomiseStrings(t);
});