Quantcast
Channel: CSSタグが付けられた新着記事 - Qiita
Viewing all articles
Browse latest Browse all 8807

JS~配列~

$
0
0

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

配列

index.js
<body><script>'use strict'constfruits=["バナナ","りんご","みかん"]document.write(fruits);</script>
</body>

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

取り出す

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

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

index.js
<script>'use strict'constfruits=["バナナ","りんご","みかん"]document.write(fruits[1]);</script>

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

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

追加、削除

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

index.js
<script>'use strict'constfruits=["バナナ","りんご","みかん"]// 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
constfruits=["バナナ","りんご","みかん"]fruits.shift();fruits.unshift("マンゴー")document.write(fruits);

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

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

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

途中の要素を追加、削除

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

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

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


Viewing all articles
Browse latest Browse all 8807

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>