0
0

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 5 years have passed since last update.

【Javascript】配列の操作いろいろ①

0
Last updated at Posted at 2020-05-12

配列とループ処理を組み合わせる##

  • for()を使う

  const scores = [10,20,50];

  for(let i = 0; i < scores.length; i++){
    //テンプレートリテラルを使う
  console.log(`Score: ${i}: ${scores[i]}`);
    //実行結果
    //Score:0:10
    //Score:1:20
    //Score:2:50
  

配列の要素を変更する##

  • push( ) pop( ) shift( ) unshift( )を使う
{
  const scores = [10,20,30];
    //配列の末尾に要素を追加
  scores.push(40,50);
  console.log(scores);
    //実行結果
    //10,20,30,40,50
}

{
  const scores = [10,20,30];
    //配列の先頭から要素を削除(1つずつしか要素を削除できないので引数は必要ない)
  scores.shift();
  console.log(scores);
    //実行結果
    //20,30,
}

//先頭に要素を追加 unshift();
//末尾から要素を削除 pop();

配列の途中の要素を操作する##

  • .splice( )を使う
{
  const scores = [10,20,50,80];

    //変数.splice(変化が開始する位置,削除数);
    //この場合20と50が削除される
  scores.splice(1,2);
  console.log(scores); 
    //実行結果 
    //10,80
}
  
{
  const scores = [10,20,50];

    //変数.splice(変化が開始する位置,削除数,追加したい要素);
    //この場合、削除は無く50の前に30と40が追加される
  scores.splice(2,0,30,40);
  console.log(scores); 
    //実行結果
    //10,20,30,40,50
}

配列に配列を埋め込む##

  • スプレット構文を使う

  const scores1 = [10,20,30,40];
  const scores2 = [50,60];

    //このscores2をscores1に入れたい場合はスプレット構文を使う。(ドット3つ)
  const scores1 = [10,20,30,40, ...scores2];
  console.log(scores1);
    //実行結果
    //10,20,30,40,50,60

配列の要素を個々の定数にする##

  • 分割代入を使う

{
  const scores = [10,20,30,40];
  //個々の要素をa,b,c,dに代入するには分割代入を使う
  const [a,b,c,d] = scores;
  console.log(a);  //10
  console.log(b);  //20
  console.log(c);  //30
  console.log(d);  //40
}

{
  const scores = [10,20,30,40];

  //定数と新たな配列を指定したい場合は分割代入とレスト構文(ドット3つ)を組み合わせて使う
  const [a,b,...other] = scores;
  console.log(a);  //10
  console.log(b);  //20
  console.log(other);  //30,40
}

分割代入の応用##


  let x = "アイス";
  let y = "チョコ";
  [x, y] = [y, x];
  console.log(x);  //チョコ
  console.log(y);  //アイス
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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?