配列への要素の追加、削除

こちらのセクションに入る前に、index.jspart3_index.jsとリネームして、index.jsを新たに作成しましょう。

ここからは配列について説明していきます。配列に関してもオブジェクトと同様にconst(定数)として定義した場合も、要素を変更することができます。要素を追加するのにpushメソッドがあります。pushメソッドは引数に渡されたものを格納することができ、複数の引数をとることができます。

index.js◎
const fruits = ['りんご', 'みかん'];
fruits.push('パイナップル', 'バナナ'); 
console.log(fruits); // ['りんご', 'みかん', 'パイナップル', 'バナナ']

またunshiftメソッドを使用すると、先頭に要素を追加することができます。

index.js◎
...
console.log(fruits);
fruits.unshift('いちご', 'メロン'); 
console.log(fruits); // ['いちご', 'メロン', 'りんご', 'みかん', 'パイナップル', 'バナナ']

要素の削除はpop,shiftメソッドを使用します。

popメソッドは、最後の要素を削除します。

index.js◎
...
console.log(fruits);
fruits.pop();
console.log(fruits); // ['いちご', 'メロン', 'りんご', 'みかん', 'パイナップル']

shiftメソッドは、最初の要素を削除します。

index.js◎
...
console.log(fruits);
fruits.shift();
console.log(fruits); // ['メロン', 'りんご', 'みかん', 'パイナップル']

Last updated