javascript - 将数组中缺少的连续数字打印为范围
问题描述
我想在范围内显示数组中未显示的数字,该数组包含范围从 1 到 128 的数字。
例如对于数组 [87,89,90,91,92,93,94,95,96,97,99]
我要打印 1-86、88、98、100-128
我写了一个函数,只有在第一个未使用的数字和最后一个数字中间没有数字时才有效
function PrintPorts(ports) {
var portString = "";
var open = true;
let index = 1
for (; index < 129; index++) {
for (let j = 0; j < ports.length; j++) {
if (index == ports[j]) {
open = false;
break;
} else
open = true;
}
if (open) {
portString += index;
break;
}
}
for (; index < 129; index++) {
for (let j = 0; j < ports.length; j++) {
if (index == ports[j]) {
open = false;
break;
} else
open = true;
}
if (!open) {
portString += "-" + (index - 1) + ",";
}
}
if (index == 129 && open) portString += "-" + (index - 1);
return portString;
}
console.log(PrintPorts([87,89,90,91,92,93,94,95,96,97,99]));
这是示例数组的结果 1-86,-88,-89,-90,-91,-92,-93,-94,-95,-96,-98,-128
当我需要的是 1-86, 88, 98, 100-128
任何帮助表示赞赏
解决方案
首先,通过使用该includes()
方法来测试数组是否包含元素来简化您的代码。
然后,用嵌套循环来做。外部循环查找范围的开始。当它找到它时,内部循环会查找范围的结尾。测试 start 和 end 是否相同,以决定是输出一个数字还是输出两个数字-
之间的数字。
生成逗号分隔字符串的最佳方法是将结果放入数组中,然后join()
在末尾使用将它们连接起来。
function PrintPorts(ports) {
var openPorts = [];
for (let index = 1; index < 129; index++) {
if (!ports.includes(index)) {
let startPort = index;
for (index = startPort + 1; index < 129; index++) {
if (ports.includes(index)) {
break;
}
}
let endPort = index - 1;
openPorts.push(startPort == endPort ? startPort : `${startPort}-${endPort}`);
}
}
return openPorts.join(",");
}
console.log(PrintPorts([87, 89, 90, 91, 92, 93, 94, 95, 96, 97, 99]));
console.log(PrintPorts([1, 2, 87, 89, 90, 91, 92, 93, 94, 95, 96, 97, 99, 120, 128]));
推荐阅读
- ios - 即使我在他们的 App Store Connect 团队中,也为我的客户的项目“注册包标识符失败”
- glsl - 只给镜头前的脸涂上红色?
- .net - IIS 代理到 SQL Server
- node-red - 如何将 cloudant out 节点与 Service External Cloudant 或 couchdb 服务一起使用?
- spring-boot - Spring boot -- Postman : 向外部发出 POST 请求
- swift - Xcode XCTest如何测试UILabel在UITesting中截断了文本
- javascript - 如何阻止 DataTable 在单击动态添加到标题的子元素时进行排序?
- python - 指定元路径的 1.0.0 中的 python pandas json_normalize - 期望可迭代
- multidimensional-array - 生成新模型 CPLEX OPL 时更改数组维度
- hibernate - 在休眠实体中用时间 api 替换 joda 时间