我有一个类似于bellow的数组:
array = [["127.0.0.1"],["127.0.0.1"],[],[]]
想要提取其中一个IP,问题是我想识别一个有IP的元素和空元素之间的区别,首先我为recognize做了一个过滤器,但现在我尝试这样做无法得到结果:
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
发布于 2020-03-25 20:56:02
我不确定我知道您要做的是什么,但是如果您确定您的数组将是空的或其中包含IP,则可能只需检查长度以查看数组中是否有任何内容。
这里我使用的是filter
函数。它接受带有参数的回调,并期望该回调返回一个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);
多亏了blex's comment,您可能希望将多维数组映射到一维。它更容易理解。如果是这样,请查看我们的their comment
https://stackoverflow.com/questions/60849224
复制相似问题