@@ -501,20 +501,39 @@ function formatObject(ctx, value, recurseTimes, visibleKeys, keys) {
501501
502502function formatArray ( ctx , value , recurseTimes , visibleKeys , keys ) {
503503 var output = [ ] ;
504- for ( var i = 0 , l = value . length ; i < l ; ++ i ) {
505- if ( hasOwnProperty ( value , String ( i ) ) ) {
506- output . push ( formatProperty ( ctx , value , recurseTimes , visibleKeys ,
507- String ( i ) , true ) ) ;
508- } else {
509- output . push ( '' ) ;
504+ // if less than a tenth of the array's slots are populated, consider it sparse
505+ // and return a compact representation. this prevents node from crashing when
506+ // calling console.log() on a small array with large length.
507+ // see https://github.com/nodejs/node/issues/4905
508+ var isSparse = value . length > 10 && keys . length * 10 < value . length ;
509+ if ( ! isSparse ) {
510+ // output a normal dense array, eg. [ , , , "foo", "bar"]
511+ for ( var i = 0 , l = value . length ; i < l ; ++ i ) {
512+ if ( hasOwnProperty ( value , String ( i ) ) ) {
513+ output . push ( formatProperty ( ctx , value , recurseTimes , visibleKeys ,
514+ String ( i ) , true ) ) ;
515+ } else {
516+ output . push ( '' ) ;
517+ }
510518 }
511519 }
520+ // output sparse arrays as eg. [10: "foo", 1000000: "bar"]
521+ // also handle additional properties on an array, for example [1, 2, 3, foo:4]
512522 keys . forEach ( function ( key ) {
523+ var str = formatProperty ( ctx , value , recurseTimes , visibleKeys , key , true ) ;
513524 if ( typeof key === 'symbol' || ! key . match ( / ^ \d + $ / ) ) {
514- output . push ( formatProperty ( ctx , value , recurseTimes , visibleKeys ,
515- key , true ) ) ;
525+ output . push ( str ) ; // str in format "foo: bar"
526+ } else if ( isSparse ) {
527+ output . push ( key + ': ' + str ) ; // str in format "bar"
516528 }
517529 } ) ;
530+ if ( isSparse ) {
531+ if ( keys . length === 0 ) {
532+ output . push ( '<empty array, length ' + value . length + '>' ) ;
533+ } else {
534+ output . push ( '<sparse array, length ' + value . length + '>' ) ;
535+ }
536+ }
518537 return output ;
519538}
520539
0 commit comments