ปัญหา
เราจำเป็นต้องเขียนฟังก์ชัน JavaScript ที่รับที่อยู่ IPv4 สองที่อยู่ และส่งกลับจำนวนที่อยู่ระหว่างกัน (รวมถึงที่อยู่แรก ไม่รวมที่อยู่สุดท้าย)
ซึ่งสามารถทำได้โดยแปลงให้เป็นทศนิยมและหาผลต่างสัมบูรณ์
ตัวอย่าง
ต่อไปนี้เป็นรหัส -
const ip1 = '20.0.0.10';
const ip2 = '20.0.1.0';
const countIp = (ip1, ip2) => {
let diff = 0;
const aIp1 = ip1.split(".");
const aIp2 = ip2.split(".");
if (aIp1.length !== 4 || aIp2.length !== 4) {
return "Invalid IPs: incorrect format";
}
for (x = 0; x < 4; x++) {
if (
isNaN(aIp1[x]) || isNaN(aIp2[x])
|| aIp1[x] < 0 || aIp1[x] > 255
|| aIp2[x] < 0 || aIp2[x] > 255
) {
return "Invalid IPs: incorrect values"
}
diff += (aIp1[x] - aIp2[x]) * (256 * (3-x));
}
return Math.abs(diff);
};
console.log(countIp(ip1, ip2)); ผลลัพธ์
ต่อไปนี้เป็นเอาต์พุตคอนโซล -
256