sortメソッドの比較関数
例えば、1〜10の数字をランダムに並べ替えたい…といった時、
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html lang="ja"> <head> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="Content-Type" content="text/html; charset=Shift_JIS"> <meta http-equiv="Content-Script-Type" content="text/javascript"> <meta http-equiv="Content-Style-Type" content="text/css"> <title>1〜10の数字をランダムに返す</title> <script type="text/javascript"> window.onload = function() { var ary = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]; ary.sort(function() { return Math.random() - Math.random();}); document.write(ary); } </script> </head> <body> </body> </html>
な簡単に出来るとは…
いつぞやのエントリで、あーだこーだやってたのが馬鹿らしいくらいスッキリしたソースです。
ただ、比較関数を引数で渡した時の処理の理屈がイマイチ理解出来てないので、
もう少しここを読んでみようと思います。