如何在Javascript中生成MAC地址? [英] How would one generate a MAC address in Javascript?
本文介绍了如何在Javascript中生成MAC地址?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要为我的项目生成随机MAC地址,我无法让它工作。下面是我当前的代码(不起作用)。
I need to generate a random MAC address for a project of mine, and I can not get it to work. Below is my current code (that is not working).
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;
}
丑陋。我对JS很新,我想知道是否有更简单的方法可以解决这个问题。
Ugly. I'm fairly new to JS and I am wondering if there is an easier way to do this that would work.
推荐答案
"XX:XX:XX:XX:XX:XX".replace(/X/g, function() {
return "0123456789ABCDEF".charAt(Math.floor(Math.random() * 16))
});
jsfiddle http ://jsfiddle.net/guest271314/qhbC9/
jsfiddle http://jsfiddle.net/guest271314/qhbC9/
这篇关于如何在Javascript中生成MAC地址?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文