迭代字符串数组会产生错误

Raf*_*sta 0 javascript

我传入一组错误消息来解析.一个示例输入是:

"An item with this x Id already exists.
 An item with this y id already exists.
 An item with this barcode already exists.
"
Run Code Online (Sandbox Code Playgroud)

也就是说,字符串实际上是每个上面用\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]  + "\"" );
  }
}
Run Code Online (Sandbox Code Playgroud)

我把它分成几行,然后遍历这些行.在索引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!
Run Code Online (Sandbox Code Playgroud)

最后一个是最离奇的:

hasObject: "function(o) {
    var l = this.length + 1;
    ... more lines ...
}
Run Code Online (Sandbox Code Playgroud)

我不明白这里发生了什么.为什么要迭代一个元素呢?为什么最后一个元素是一个函数?并且不应该偏移3是一个空字符串?那就是我不应该警告"错误!" 这里.

jba*_*bey 5

永远不要使用for ... in循环数组.

以任意顺序迭代对象的可枚举属性.

为什么在数组迭代中使用"for ... in"是一个坏主意?

  • 这不回答这个问题. (2认同)