前回記事JavaScript入門4では関数の書き方について学びました。今回は配列について考えていきます。10月25日記事
目次
配列の表現について、連想配列は今後学ぶオブジェクトと似ています。連想配列はオブジェクトの一種だと考えていいです。最後の方はオブジェクトとしての書き方も少しふれておきます。
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>配列</title>
</head>
<body>
<script>
//基本的な使い方
var testscore = [98,30,100];
console.log(testscore[0]);//0から開始される。98が表示される。
//連想配列の書き方
var testscore1 = {
math: 98,
japanese: 30,
english: 100
};
console.log(testscore1["math"]);
var testscore2 = {
"math": 98,
"japanese": 30,
"english": 100
};
console.log(testscore2["math"]);//ダブルクオーテーション等でくくる。
console.log(testscore2.math);//こんな感じでも使える。オブジェクトの使い方
//console.log(testscore2[0]);//これはエラーが表示されます。
//値を書き換える場合
testscore2.math = 100;
console.log(testscore2.math);
</script>
</body>
</html>
連想配列は次に出てくるオブジェクトを使う表現と同じです。連想配列=オブジェクトの表現と考えておくと、よりオブジェクトの学習が楽になると思います。
以上