我有这个程序来识别URL在消息中的位置并且只在URL中保留字符串,但它只是随机跳过值而我不知道为什么。这是我的代码和调试控制台。
function DeleteNonURL(sep, URL)
{
var _Pos = new Number;
URL = URL.split(sep);
for (var i = 0; i < URL.length; i++)//deletes non-url substrings
{
Debug.Trace("Msg: "+URL + " i: "+i + " _Pos: "+_Pos + " Current Substring: "+URL[i]);
_Pos = URL[i].indexOf('.com');
if(_Pos == -1)
{
_Pos = URL[i].indexOf('.net');
if(_Pos == -1)
{
_Pos = URL[i].indexOf('.org');
if(_Pos == -1)
{
_Pos = URL[i].indexOf('.info');
if(_Pos == -1) //No URL in this substr
{
URL.splice(i, 1); //deleted.
}
}
}
}
}
Debug.Trace(URL);
}
Debug:
Msg: Hey,dude,look,at,this,amazon.com,what,is,it? i: 0 _Pos: 0 Current Substring: Hey
Msg: dude,look,at,this,amazon.com,what,is,it? i: 1 _Pos: -1 Current Substring: look
Msg: dude,at,this,amazon.com,what,is,it? i: 2 _Pos: -1 Current Substring: this
Msg: dude,at,amazon.com,what,is,it? i: 3 _Pos: -1 Current Substring: what
Msg: dude,at,amazon.com,is,it? i: 4 _Pos: -1 Current Substring: it?
dude,at,amazon.com,is
答案 0 :(得分:0)
正如评论中所指出的,当突变导致数组重新编制索引时,这是一个非常普遍的变异问题,即你正在迭代的数组。
最终,您似乎想要检查以其中一个TLD结尾的子字符串。这可以更简单地完成。
const re = /\.(?:com|net|org|info)$/;
function test(sep, URL) {
return URL.split(sep).find(s => re.test(s));
}
const a = "http://example.com/foo/bar";
const b = "foo/bar/baz";
console.log("TLD part", test('/', a));
console.log("TLD part", test('/', b));
&#13;