如何在Javascript中生成MAC地址?

前端之家收集整理的这篇文章主要介绍了如何在Javascript中生成MAC地址?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我需要为我的一个项目生成一个随机的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;

}

丑陋.我对JS很新,我想知道是否有更简单的方法来做到这一点.

解决方法

这是一个更多的“干净”版本的代码,这将循环次数减少到一个.在循环的每次迭代中,它将两个随机字符附加到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;
}

除了比必要的更复杂,你的代码有两个问题.第一个是由于破折号,mac-address是一个无效的变量名.这导致代码根本不起作用.有了这个修复,另一个问题是在最后设置MAC地址变量时,将数组附加到字符串.这导致每个包含两个十六进制数字的数组被转换成一个字符串,这意味着一个逗号被放在两位数之间.

猜你在找的JavaScript相关文章