Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript - Google Chrome cluttering Array generated from .split()

Given the following string:

var str = "one,two,three";

If I split the string on the commas, I normally get an array, as expected:

var arr = str.split(/\s*,\s*/);

Trouble is that in Google Chrome (for Mac), it appends extra properties to the array.

Output from Chrome's debugger:

arr: Array
    0: one
    1: two
    2: three
    constructor: function Array()
    index: undefined
    input: undefined
    length: 3

So if I iterate over the array with a for/in loop, it iterates over the new properties. Specifically the input and index properties. Using hasOwnProperty doesn't seem to help.

A fix would be to do a for loop based on the length of the Array. Still I'm wondering if anyone has insight into why Chrome behaves this way. Firefox and Safari don't have this issue.

like image 286
user113716 Avatar asked Dec 03 '22 12:12

user113716


2 Answers

Don't iterate over arrays using for...in loops!! This is one of the many pitfalls of Javascript (plug) - for...in loops are for iterating over object properties only.

Use normal for loops instead.

for (var i=0, max = arr.length; i < max; i++) { ... } 


Firefox and Safari's ECMAScript/Javascript engines make those particular properties non-enumerable ({DontEnum} attribute), so they would not be iterated over in a for...in loop. Still, for...in loops were not intended to iterate over array indexes.
like image 157
Andy E Avatar answered Dec 06 '22 10:12

Andy E


For..in is for iterating over enumerable properties of objects. For an array, to iterate over its indicies, just use a standard for loop

for ( var i = 0, l = arr.length, i < l; i++ )
{
  // do whatever with arr[i];
}
like image 41
Peter Bailey Avatar answered Dec 06 '22 09:12

Peter Bailey