use*_*580 9 javascript arrays search
我有这样的数组
var ALLOW_SUBNET = ['192.168.1.', '192.168.2.', '192.168.3.' , '192.168.4.'];
Run Code Online (Sandbox Code Playgroud)
我可以使用自己的函数获取PC Client的IP地址:
getIPClient()
var ipclient = input.getIPClient();
Run Code Online (Sandbox Code Playgroud)
我的问题是如何检查客户端IP是否在我允许的子网内,我尝试使用indexOf()函数,但结果是错误的.例如:
if IP Client is 192.168.1.115 => allow
if IP Client is 192.168.5.115 => deny.
Run Code Online (Sandbox Code Playgroud)
Nin*_*olz 10
你可以使用Array#some
它并检查一部分ALLOW_SUBNET
是否ip
在位置内0
.
function check(ip) {
return ALLOW_SUBNET.some(function (a) { return !ip.indexOf(a); });
}
var ALLOW_SUBNET = ['192.168.1.', '192.168.2.', '192.168.3.', '192.168.4.'];
console.log(check('192.168.1.115'));
console.log(check('192.168.5.115'));
Run Code Online (Sandbox Code Playgroud)
ES6用 String#startsWith
function check(ip) {
return ALLOW_SUBNET.some(a => ip.startsWith(a));
}
var ALLOW_SUBNET = ['192.168.1.', '192.168.2.', '192.168.3.', '192.168.4.'];
console.log(check('192.168.1.115'));
console.log(check('192.168.5.115'));
Run Code Online (Sandbox Code Playgroud)
这是一个解决方案.
var ALLOW_SUBNET = ['192.168.1.', '192.168.2.', '192.168.3.', '192.168.4.'];
function checkIP(ip) {
var allow = false;
for (var i = 0; i <= ALLOW_SUBNET.length; i++) {
if (ip.indexOf(ALLOW_SUBNET[i]) > -1) {
allow = true;
break;
}
}
return allow;
}
console.log(checkIP('192.168.9.3'));
console.log(checkIP('192.168.1.3'));
Run Code Online (Sandbox Code Playgroud)