Iterating over array of strings produces error

前端 未结 4 1292
太阳男子
太阳男子 2021-01-26 13:22

I pass in an array of error messages to parse. An example input would be:

\"An item with this x Id already exists.
 An item with this y id already exists.
 An it         


        
4条回答
  •  孤街浪徒
    2021-01-26 14:09

    As jbabey said, using for .. in loops in Javascript is risky and undeterministic (random order--sometimes). You would most commonly use that for parsing through objects in associative arrays. But, if you insist on keeping the for .. in, wrap the inside of the for with an if block like such:

    for (var i in aLines)
    {
        if(aLines.hasOwnProperty(i))
        {
            // ... Do stuff here
        }
    }
    

    Otherwise, just change it to a classic incremental for loop to get rid of that error:

    for (var i = 0; i < aLines.length; i++)
    {
       if ( !aLines[i] ) { alert( "Error!" ); continue; }
       alert( i + ": \"" + aLines[i]  + "\"" );
    }
    

提交回复
热议问题