How would one generate a MAC address in Javascript?

后端 未结 3 747
温柔的废话
温柔的废话 2021-02-07 15:48

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(){
/         


        
3条回答
  •  天命终不由人
    2021-02-07 16:27

    try this Jsfiddle

    all i did was to fix the display part :

    function genMAC(){
    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
    var partA = new Array(1);
    var partB = new Array(1);
    var partC = new Array(1);
    var partD = new Array(1);
    var partE = new Array(1);
    var partF = new Array(1);
    var 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[0]+ partA[1] + ":" + partB[0]+ partB[1] + ":" + partC[0]+ partC[1] + ":" + partD[0] + partD[1] + ":" + partE[0] + partE[1] + ":" + partF[0] + partF[1];
    alert(mac_address);
    }
    

    if you just print/alert the array for example partA it would display like 3,2 and not 32 so you need to concatenate it each index it has.

提交回复
热议问题