LoginSignup
0
0

More than 3 years have passed since last update.

今回は、JSで配列を作っていきます!

配列

index.js
<body>
  <script>
    'use strict'

    const fruits = ["バナナ", "りんご", "みかん"]
    document.write(fruits);
  </script>
</body>

定数にフルーツを代入していきます。今回は、バナナとりんごとみかんを並べました。
ブラウザで表示すると以下のようになります。
スクリーンショット 2021-04-05 10.23.17.png

取り出す

では、この配列から1つ取り出して行きたいと思います。

配列は、左から順番に0番目と考えます。
今回は、りんごを取り出したいと思います。

index.js
<script>
    'use strict'

    const fruits = ["バナナ", "りんご", "みかん"]

    document.write(fruits[1]);
  </script>

今回のりんごは1番目の配列になります。

スクリーンショット 2021-04-05 10.27.10.png

追加、削除

次に、この配列に追加と削除をしていきたいと思います。

index.js
<script>
    'use strict'

    const fruits = ["バナナ", "りんご", "みかん"]
    // document.write(fruit);
    // document.write(fruit[1]);
    fruits.pop();
    fruits.push("もも");
    document.write(fruits);
 </script>

popで末尾のみかんを削除して、pushで末尾にももを追加しました。

スクリーンショット 2021-04-05 10.43.54.png

index.js
const fruits = ["バナナ", "りんご", "みかん"]
    fruits.shift();
    fruits.unshift("マンゴー")
    document.write(fruits);

文頭のバナナを削除し、マンゴーを追加しました。

スクリーンショット 2021-04-05 11.57.34.png

*pushとunshifyは一度に複数の要素を追加することができます。

途中の要素を追加、削除

削除数よりも多い数を追加する場合に使います。

index.js
<script>
    'use strict'

    const fruits = ["バナナ", "りんご", "みかん"]
    fruits.shift();
    fruits.unshift("マンゴー");
    fruits.splice(1,2,"さくらんぼ","ぶどう");
    document.write(fruits);
  </script>

以下のようになりました!!
スクリーンショット 2021-04-05 12.11.24.png

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0