array.reverse()メソッドは、配列要素を逆順に並べ替え、並び替え後の配列を返すメソッド。
構文
array.reverse()
戻り値
並び替え後の配列。
サンプル
文字列
<script type="text/javascript">
var $sampleArray = new Array( '要素3', '要素4', '要素2', '要素5', '要素1' );
document.write( '$sampleArray: ' + $sampleArray + '<br />' );
var $sampleArraySort = $sampleArray.sort();
document.write( '$sampleArraySort: ' + $sampleArraySort + '<br />' );
var $sampleArrayReverse = $sampleArraySort.reverse();
document.write( '$sampleArrayReverse: ' + $sampleArrayReverse + '<br />' );
document.write( '$sampleArray: ' + $sampleArray + '<br />' );
</script>
var $sampleArray = new Array( '要素3', '要素4', '要素2', '要素5', '要素1' );
document.write( '$sampleArray: ' + $sampleArray + '<br />' );
var $sampleArraySort = $sampleArray.sort();
document.write( '$sampleArraySort: ' + $sampleArraySort + '<br />' );
var $sampleArrayReverse = $sampleArraySort.reverse();
document.write( '$sampleArrayReverse: ' + $sampleArrayReverse + '<br />' );
document.write( '$sampleArray: ' + $sampleArray + '<br />' );
</script>
↓↓↓出力結果↓↓↓
数値
<script type="text/javascript">
function compareFunction( $a, $b ) {
if ( $a == $b )
return 0;
if ( $a < $b )
return -1;
else
return 1;
}
var $sampleArray = new Array( 3, 12, 8, 21, 1 );
document.write( '$sampleArray: ' + $sampleArray + '<br />' );
var $sampleArraySort = $sampleArray.sort( compareFunction );
document.write( '$sampleArraySort: ' + $sampleArraySort + '<br />' );
var $sampleArrayReverse = $sampleArraySort.reverse();
document.write( '$sampleArrayReverse: ' + $sampleArrayReverse + '<br />' );
document.write( '$sampleArray: ' + $sampleArray + '<br />' );
</script>
function compareFunction( $a, $b ) {
if ( $a == $b )
return 0;
if ( $a < $b )
return -1;
else
return 1;
}
var $sampleArray = new Array( 3, 12, 8, 21, 1 );
document.write( '$sampleArray: ' + $sampleArray + '<br />' );
var $sampleArraySort = $sampleArray.sort( compareFunction );
document.write( '$sampleArraySort: ' + $sampleArraySort + '<br />' );
var $sampleArrayReverse = $sampleArraySort.reverse();
document.write( '$sampleArrayReverse: ' + $sampleArrayReverse + '<br />' );
document.write( '$sampleArray: ' + $sampleArray + '<br />' );
</script>
↓↓↓出力結果↓↓↓