我传递一个错误消息数组来解析。一个示例的输入将是:迭代字符串数组会产生错误
"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是一个空字符串?那就是我不应该提醒“错误!”这里。
您应该检查aLines'的'长度,并确保它是因为在最后一行的末尾一个断行的不是4。 –
'split'在这种情况下将返回4段。最后一段是一个空字符串('“”'),但不是'null'或'undefined'。如果它自己在一行上,你需要忽略最后一个'\ n'。 – Zabba
问题已解决。每个答案都是正确的。谢谢。 –