我需要为我的项目生成随机MAC地址,我无法让它工作.以下是我当前的代码(不起作用).
function genMAC(){
// Make a new array with all available HEX options.
var colours = new Array("0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F");
// Make variable to hold 6 character HEX array
partA = new Array(1);
partB = new Array(1);
partC = new Array(1);
partD = new Array(1);
partE = new Array(1);
partF = new Array(1);
mac-address="";
for (i=0;i<2;i++){
// Loop for partA
partA[i]=colours[Math.round(Math.random()*14)];
}
for (i=0;i<2;i++){
// Loop through 6 times, randomising the letter added to the array
partB[i]=colours[Math.round(Math.random()*14)];
}
for (i=0;i<2;i++){
// Loop through 6 times, randomising the letter added to the array
partC[i]=colours[Math.round(Math.random()*14)];
}
for (i=0;i<2;i++){
// Loop through 6 times, randomising the letter added to the array
partD[i]=colours[Math.round(Math.random()*14)];
}
for (i=0;i<2;i++){
// Loop through 6 times, randomising the letter added to the array
partE[i]=colours[Math.round(Math.random()*14)];
}
for (i=0;i<2;i++){
// Loop through 6 times, randomising the letter added to the array
partF[i]=colours[Math.round(Math.random()*14)];
}
// Returns like "a10bc5". It is likely that you may need to add a "#".
mac-address = partA + ":" + partB + ":" + partC + ":" + partD + ":" + partE + ":" + partF;
return mac-address;
Run Code Online (Sandbox Code Playgroud)
}
丑陋.我是JS的新手,我想知道是否有一种更简单的方法可以做到这一点.
gue*_*314 27
"XX:XX:XX:XX:XX:XX".replace(/X/g, function() {
return "0123456789ABCDEF".charAt(Math.floor(Math.random() * 16))
});
Run Code Online (Sandbox Code Playgroud)
jsfiddle http://jsfiddle.net/guest271314/qhbC9/
D. *_*out 10
这里有一些代码的"干净"版本,它将循环次数减少到一次.在循环的每次迭代中,它将两个随机字符附加到macAddress变量,如果它不是最后一次迭代,它还会附加一个冒号.然后它返回生成的地址.
function genMAC(){
var hexDigits = "0123456789ABCDEF";
var macAddress = "";
for (var i = 0; i < 6; i++) {
macAddress+=hexDigits.charAt(Math.round(Math.random() * 15));
macAddress+=hexDigits.charAt(Math.round(Math.random() * 15));
if (i != 5) macAddress += ":";
}
return macAddress;
}
Run Code Online (Sandbox Code Playgroud)
除了比必要更复杂之外,您的代码还有两个问题.第一个是mac-address由于破折号而导致的无效变量名称.这导致代码根本不起作用.解决了这个问题后,另一个问题是,在最后设置MAC地址变量时,会将数组附加到字符串中.这导致每个包含两个十六进制数字的数组被转换为字符串,这意味着在两个数字之间放置一个逗号.
| 归档时间: |
|
| 查看次数: |
4263 次 |
| 最近记录: |