在阵列中,我如何识别它们是 IP 的元素?

In array,How I can make recognition between elements that are they IP?

我有一个数组,如下所示:

array = [["127.0.0.1"],["127.0.0.1"],[],[]]

并想提取其中一个 IP,问题是我想识别具有 IP 的元素和空元素之间的区别,首先我为识别数字制作了一个过滤器,但现在我无法获得结果尝试这种方式:

let IpString = array.split("\"");

///and gave me this bellow result

Array(5) ["[[", "127.0.0.1", "],[", "127.0.0.1", "],[],[]]"]
browser_prototype.js:268
length:5
__proto__:Array(0) [, …]
0:"[["
1:"127.0.0.1"
2:"],["
3:"127.0.0.1"
4:"],[],[]]"

但我认为我应该找到一种可以识别空元素和 IP 元素的方法,然后我只需要一个 IP,因为始终存在相同和相等的元素。 我正在寻找以下结果:

127.0.0.1

我不确定我明白你想做什么,但是如果你确定你的数组是空的或者里面有 IP,你可能只需要检查长度看看是否有是数组中的任何内容。

这里我使用的是filter函数。它需要一个带参数的回调,并期望回调到 return a boolean

const array = [["127.0.0.1"],["127.0.0.1"],[],[]];
// we use the filter function to check for the length of each sub-arrays.
// here, a length of 0 would evaluate as falsy, thus not including the empty array.
const ips = array.filter(item => item.length);
console.log(ips.length);

可选,感谢, you might want to map your multi-dimensionnal array to a single dimension. It's easier for comprehension. If so, check our