Как можно создать MAC-адрес в Javascript?
Мне нужно создать случайный 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, и мне интересно, есть ли более простой способ сделать это, чтобы это работало.
Ответы
Ответ 1
Вот немного более "чистая" версия вашего кода, в которой количество циклов уменьшается до одного. На каждой итерации цикла он добавляет два случайных символа к переменной 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-адреса в конце вы добавляли массивы в строку. Это привело к тому, что каждый из массивов, содержащих две шестнадцатеричные цифры, был преобразован в строку, что означало, что между двумя цифрами была помещена запятая.
Ответ 2
"XX:XX:XX:XX:XX:XX".replace(/X/g, function() {
return "0123456789ABCDEF".charAt(Math.floor(Math.random() * 16))
});
jsfiddle http://jsfiddle.net/guest271314/qhbC9/
Ответ 3
попробуйте Jsfiddle
все, что я сделал, это исправить часть дисплея:
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);
}
если вы просто печатаете/предупреждаете массив, например partA
, он будет отображаться как 3,2
, а не 32
, поэтому вам нужно объединить его в каждый его индекс.