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

标签 javascript

我传入一组错误消息进行解析。输入示例如下:

"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.

Why is using "for...in" with array iteration a bad idea?

关于javascript - 迭代字符串数组会产生错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12980860/

相关文章:

javascript - 选择一个给定存储在字符串中的 div 名称的对象

javascript - 无法从 Angular 9 中的服务加载变量

javascript - 从对象中查找并删除空属性

javascript - AngularJS 变量之间的绑定(bind)

javascript - 如何更改CKEditor的编辑器大小?

javascript - 我想创建对象类型数组,for循环只压入最后一个值,为什么?

javascript - 如何在 Node.js 中读取文件?

javascript - 复制数组 --> 堆栈或堆溢出?

java - 将 JS 变量传递给 java 类

javascript - 为什么选择不下拉?