javascript array.sort with undefined values

后端 未结 3 1072
自闭症患者
自闭症患者 2020-12-06 16:50

How does Array.prototype.sort handle undefined values in an array?

var array = [1,undefined,2,undefined,3,undefined,4];
var array2 = [];
array2[         


        
3条回答
  •  心在旅途
    2020-12-06 17:22

    It appears that the undefined values will fall to the bottom of the list. Here's some sample code to show you what happens:

    var a = [1,undefined,2,undefined,3,undefined,4];
      a = a.sort();
      for( i = 0 ; i < a.length ; i++ )
      {
        alert( a[i] );
      }
    

    This is, of course, the default behavior of JavaScript. If you overwrite the default behavior then only you will know.

提交回复
热议问题