我传入一组错误消息进行解析。输入示例如下:
"An item with this x Id already exists.
An item with this y id already exists.
An item with this barcode already exists.
"
也就是说,字符串实际上是上面的每一行都用\n 分隔,最后有一个\n。
function( msg )
{
alert( "\"" + msg + "\"" );
var aLines = msg.split( /\r?\n+/ );
for ( var i in aLines )
{
if ( !aLines[i] ) { alert( "Error!" ); continue; }
alert( i + ": \"" + aLines[i] + "\"" );
}
}
我将其分成几行,然后迭代这些行。在索引 3 处,没有行并且第一个条件触发器。那不应该是一个空行吗?例如“”
然后循环实际上又增加了一个元素到 4,并显示了函数的内容。
我收到了 - 五个警报:
0: "An item with this x Id already exists."
1: "An item with this y id already exists."
2: "An item with this barcode already exists."
Error!
最后一个是最奇怪的:
hasObject: "function(o) {
var l = this.length + 1;
... more lines ...
}
我不明白这里发生了什么。为什么它要迭代另一个元素?为什么最后一个元素是一个函数?偏移量 3 不应该是一个空字符串吗?也就是说,我不应该警告“错误!”在这里。
最佳答案
Never loop over an array with for...in.
Iterates over the enumerable properties of an object, in arbitrary order.
关于javascript - 迭代字符串数组会产生错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12980860/