Iterating over array of strings produces error

前端 未结 4 1289
太阳男子
太阳男子 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:01

    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?

    0 讨论(0)
  • 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]  + "\"" );
    }
    
    0 讨论(0)
  • 2021-01-26 14:09

    You are getting Error! in end because the splitting is giving you empty line "" and when you check for it with if(!aLines[i]) it returns true because it is empty/null/nothing. You can check it here in a fiddle, you remove the empty line from end and it does not go over array 4 times.

    I have also put in following code which shows alert:

        var a="";
        if(!a){
            alert("!a");
        }
    
    0 讨论(0)
  • 2021-01-26 14:21

    You should use a regular for loop for arrays, because for-in will also return all the other property keys in the Array object. This is why you are seeing "hasObject" (and in my browser, I see a lot more after that): because your array has the function "hasObject", so when you enumerate all of Array's properties this comes up.

    The correct for-loop:

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

    Here is your code with the for-in loop replaced with a for loop, and it works as expected:

    http://jsfiddle.net/SamFent/4rzTh/

    0 讨论(0)
提交回复
热议问题