JavaScriptの配列リテラルについて。
構文
値、式、変数などをカンマ区切りで羅列し、角括弧[]
で括る。
[ 値1, 値2, 値3, …値N ]
[ 式1, 式2, 式3, …式N ]
[ 変数1, 変数2, 変数3, …変数N ]
サンプル
数値
<script type="text/javascript">
var $arrayNum = [ 2, 5, 10 ];
document.write( $arrayNum[0] + '<br />' );
document.write( $arrayNum[1] + '<br />' );
document.write( $arrayNum[2] + '<br />' );
</script>
var $arrayNum = [ 2, 5, 10 ];
document.write( $arrayNum[0] + '<br />' );
document.write( $arrayNum[1] + '<br />' );
document.write( $arrayNum[2] + '<br />' );
</script>
↓↓↓出力結果↓↓↓
文字列
<script type="text/javascript">
var $arrayStr = [ 'a', 'b', 'c' ];
document.write( $arrayStr[0] + '<br />' );
document.write( $arrayStr[1] + '<br />' );
document.write( $arrayStr[2] + '<br />' );
var $arrayStr = [ '文字列A', '文字列B', '文字列C' ];
document.write( $arrayStr[0] + '<br />' );
document.write( $arrayStr[1] + '<br />' );
document.write( $arrayStr[2] + '<br />' );
</script>
var $arrayStr = [ 'a', 'b', 'c' ];
document.write( $arrayStr[0] + '<br />' );
document.write( $arrayStr[1] + '<br />' );
document.write( $arrayStr[2] + '<br />' );
var $arrayStr = [ '文字列A', '文字列B', '文字列C' ];
document.write( $arrayStr[0] + '<br />' );
document.write( $arrayStr[1] + '<br />' );
document.write( $arrayStr[2] + '<br />' );
</script>
↓↓↓出力結果↓↓↓
式
<script type="text/javascript">
var $arrayExpression = [ 3*1, 3*2, 3*3 ];
document.write( $arrayExpression[0] + '<br />' );
document.write( $arrayExpression[1] + '<br />' );
document.write( $arrayExpression[2] + '<br />' );
</script>
var $arrayExpression = [ 3*1, 3*2, 3*3 ];
document.write( $arrayExpression[0] + '<br />' );
document.write( $arrayExpression[1] + '<br />' );
document.write( $arrayExpression[2] + '<br />' );
</script>
↓↓↓出力結果↓↓↓
変数
<script type="text/javascript">
var $varA = 2;
var $varB = $varA + 3;
var $varC = '文字列';
var $arrayVar = [ $varA, $varB, $varC ];
document.write( $arrayVar[0] + '<br />' );
document.write( $arrayVar[1] + '<br />' );
document.write( $arrayVar[2] + '<br />' );
</script>
var $varA = 2;
var $varB = $varA + 3;
var $varC = '文字列';
var $arrayVar = [ $varA, $varB, $varC ];
document.write( $arrayVar[0] + '<br />' );
document.write( $arrayVar[1] + '<br />' );
document.write( $arrayVar[2] + '<br />' );
</script>
↓↓↓出力結果↓↓↓