JS~配列~
今回は、JSで配列を作っていきます!
配列
index.js
<body>
<script>
'use strict'
const fruits = ["バナナ", "りんご", "みかん"]
document.write(fruits);
</script>
</body>
index.js
<body>
<script>
'use strict'
const fruits = ["バナナ", "りんご", "みかん"]
document.write(fruits);
</script>
</body>
定数にフルーツを代入していきます。今回は、バナナとりんごとみかんを並べました。
ブラウザで表示すると以下のようになります。
取り出す
では、この配列から1つ取り出して行きたいと思います。
配列は、左から順番に0番目と考えます。
今回は、りんごを取り出したいと思います。
index.js
<script>
'use strict'
const fruits = ["バナナ", "りんご", "みかん"]
document.write(fruits[1]);
</script>
今回のりんごは1番目の配列になります。
追加、削除
次に、この配列に追加と削除をしていきたいと思います。
index.js
<script>
'use strict'
const fruits = ["バナナ", "りんご", "みかん"]
// document.write(fruit);
// document.write(fruit[1]);
fruits.pop();
fruits.push("もも");
document.write(fruits);
</script>
popで末尾のみかんを削除して、pushで末尾にももを追加しました。
index.js
const fruits = ["バナナ", "りんご", "みかん"]
fruits.shift();
fruits.unshift("マンゴー")
document.write(fruits);
文頭のバナナを削除し、マンゴーを追加しました。
*pushとunshifyは一度に複数の要素を追加することができます。
途中の要素を追加、削除
削除数よりも多い数を追加する場合に使います。
index.js
<script>
'use strict'
const fruits = ["バナナ", "りんご", "みかん"]
fruits.shift();
fruits.unshift("マンゴー");
fruits.splice(1,2,"さくらんぼ","ぶどう");
document.write(fruits);
</script>
Author And Source
この問題について(JS~配列~), 我々は、より多くの情報をここで見つけました https://qiita.com/akari_0618/items/a832534dd3b2d3b39911著者帰属:元の著者の情報は、元のURLに含まれています。著作権は原作者に属する。
Content is automatically searched and collected through network algorithms . If there is a violation . Please contact us . We will adjust (correct author information ,or delete content ) as soon as possible .