我传入一个要解析的错误消息数组。一个输入示例是:
"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,并显示一个函数的内容。
这就是我得到的-5个警报:
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不应该是空字符串吗?那就是我不应该警告“错误!”这里。
发布于 2012-10-20 03:33:49
您最终得到的是Error!,因为拆分得到的是空行"",而当您使用if(!aLines[i])检查它时,它会返回true,因为它是空/null/nothing。你可以在fiddle中检查它,你从end中删除空行,它不会遍历数组4次。
我还添加了以下代码来显示警报:
var a="";
if(!a){
alert("!a");
}https://stackoverflow.com/questions/12980860
复制相似问题