1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

概要

JSでは配列が最も多く使われるデータ構造です。配列には様々なメソッドが用意されています。
この記事では配列操作について触れていきます。

index.js
const fruits = ["りんご", "ばなな", "ぶどう", "いちご"];
const fruits2= ["パパイヤ", "パイナップル", "みかん",];

今回使用する元の配列です。

値の追加と削除

arrayオブジェクトには、配列の先頭、末尾に要素を追加または削除するメソッドが用意されています。

1.追加

(1)push

index.js
const fruits = ["りんご", "ばなな", "ぶどう", "いちご"];
const fruits2= ["パパイヤ", "パイナップル", "みかん",];

fruits.push("パパイヤ","パイナップル"); 
console.log(fruits);
//["りんご", "ばなな", "ぶどう", "いちご","パパイヤ","パイナップル"] 

fruitsとfruits2という2つの配列があります。fruits2の要素をfruitsに追加します。
となります。push()に引数を追加します。複数追加したときは最後の引数が末尾になります。

(2)unshift

index.js
fruits.unshift("パパイヤ","パイナップル");
//["パパイヤ","パイナップル","りんご", "ばなな", "ぶどう", "いちご"]

こちらは要素を先頭に追加します。
複数追加したときは、最初の引数が先頭になります。

削除

(1)pop

index.js
fruits.pop();
console.log(fruits);
//[["りんご", "ばなな", "ぶどう"]

末尾から要素を取り除きます。

(2)shift

index.js
fruits.shift();
console.log(fruits);
//["ばなな", "ぶどう","いちご"]

先頭から要素を削除します。

配列の結合と分離

配列は、複数の配列を結合した新しい配列を作る。配列の一部から新しい配列を作ったりすることができます。

1.concat

index.js
 console.log(fruits.concat(fruits2));
 console.log(fruits);

//["りんご", "ばなな", "ぶどう", "いちご","パパイヤ", "パイナップル", "みかん"]
//["りんご", "ばなな", "ぶどう", "いちご"]

引数の配列の要素、引数の値を順に並べた新しい配列を作ります。
元の配列は影響を受けません。

2.slice

index.js
console.log(fruits.slice(1,3));
console.log(fruits.slice(2));
console.log(fruits);

//["ばなな","ぶどう"]
//["ぶどう", "いちご"]
//["りんご", "ばなな", "ぶどう", "いちご"]

第1引数から第2引数の手前までをの要素の新しい配列を作ります。
また引数が1つだった場合は、引数から末尾の要素までの新しい要素を作ります。
元の配列は影響を受けません。

3.splice

index.js
console.log(fruits.splice(1,2,"マンゴー","キウイ"));
console.log(fruits);

//["ばなな","ぶどう"]
//["りんご", "マンゴー", "キウイ", "いちご"]

第1引数が要素インデックス番号、削除する数。更に追加する要素を記述します。
もとの配列は影響をうけます。

1
1
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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?