JavaScript - 如何增加计数

时间:2018-06-01 03:15:03

标签: javascript servicenow

当我给出带有当前下面脚本的IP(10.31.68.0/22)变量时,它将返回 输出: 10.31.68.1 - 10.31.68.10

var network = '10.31.68.0/22';
var IPstart = network.toString().substring(0,network.lastIndexOf('.')) + ".1";                      
var IPend = network.toString().substring(0,network.lastIndexOf('.')) + ".10";               
var excludename = IPstart+"-"+IPend;

我正在寻找下面的东西(输出)。 68占位符应增加+1,如下所示。

10.31.68.1 - 10.31.68.10

10.31.69.1 - 10.31.69.10

10.31.70.1 - 10.31.70.10

10.31.71.1 - 10.31.71.10

2 个答案:

答案 0 :(得分:1)

您需要使用循环

拆分和连接值



var network = '10.31.68.0/22';
    var IPstart = network.toString().substring(0,network.lastIndexOf('.')) + ".1";
    var IPend = network.toString().substring(0,network.lastIndexOf('.')) + ".10";
    var excludename = IPstart+"-"+IPend;
    var upToNumber=4;
    for(var i=0;i<upToNumber;i++){
        var res_ipstart = IPstart.split(".");
    res_ipstart[2]=parseInt(res_ipstart[2]) + i;
    var ip_start = res_ipstart.join(".");

        var res_ipend = IPend.split(".");
    res_ipend[2]=parseInt(res_ipend[2]) + i;
    var ip_end = res_ipend.join(".");

    var output=ip_start+"-"+ip_end;
    console.log(output);
    }
&#13;
&#13;
&#13;

答案 1 :(得分:1)

这应该做:

&#13;
&#13;
/* Remove the slash */
let rawIp = "10.31.68.1/22";
let rawIpParts = rawIp.split("/");

/* Split the new ip */
let ip = rawIpParts[0];
let ipParts = ip.split(".")

/* Append 0 */
ipParts[3] = ipParts[3].concat("0");

/* Output Array */
let output = []

/* Loop and increment */
for(let index = 0; index <= 4; index++) {
  ipParts[2] = 1 + +ipParts[2];
  output.push(ipParts.join("."));
}

/* Print */
console.log(output);
&#13;
&#13;
&#13;

希望这有帮助!