sort()排序
sort()内的排序函数,如果返回的不是数值,ie下会停止程序执行
by calefy
HTML
<h1>sort()</h1>
<p>
sort()方法中调用排序函数,如果返回的不是数值,那么在ie6下将会中断执行,但是不会有任何错误触发。
<br/>
返回的数如果是“-20”等会如何
</p>
<hr/>
CSS
p{margin:0;}
.compare{padding:10px 0;border-bottom:1px dotted #f60;}
.compare label,
.compare span{width:4em;display:inline-block;*display:inline;*zoom:1;}
.compare span{width:7em}
JavaScript
/** 执行排序
* @param {Array} arr
* @param {Boolean} r
*/
function execSort(arr, r, noProgress) {
var html = [],
number = 1,
copy = arr.slice(0);
window.console && window.console.log('排列前:', arr);
html.push('<div class="compare">');
html.push('<p>排列前:<br/> ' + arr.join(' - ') + ' </p>');
// sort()
copy.sort();
arr.sort(function(a, b) {
var v = r ? b - a : a - b;
if (!noProgress) {
html.push('<p>');
html.push('<label>比较' + number + ': </label><span>' + (r ? (b + ' - ' + a) : (a + ' - ' + b)) + ' </span>= ' + v);
html.push('</p>');
}
if (isNaN(v)) {
html.push('is NaN on '+number+'<br/>');
}
number++;
return v;
});
html.push('<p>排列后:<br/> ' + 'custom: ' + arr.join(' - ') + '<br/> default: ' + copy.join(' - ') + ' </p>');
html.push('</div>');
// 输出
window.console && window.console.log('排列后custom:', arr, 'default: ',copy);
document.write(html.join(''));
}
// 纯类型比较
execSort([5, 3, 8, 23, 1, 9, 2, 13], false, true);
execSort(['hello', 'Hello', 'hEllo', 'HEllo']);
// 混合
execSort([undefined,5,null,2,27,undefined,8,'He',54,'he',null,'HE',undefined,13,'uuef','nvll','ntll',false,'fblse','fakse'],false,true);
// undefined 不会传递给自定义比较函数(过程中没有undefined)
execSort([3,undefined,14,null], false, false);
// 稳定性
var ta = [{a:1,b:2},{a:23,b:3},{a:1,b:4}];
function trun(){
ta.sort(function(a,b){
return a.a - b.a;
});
console.log(ta[0].b,ta[1].b,ta[2].b);
}
trun();trun();trun();