1
2

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.

JavaScriptの配列とオブジェクト操作

Last updated at Posted at 2020-04-01

配列操作


  const a = [1, 2, 3, 4, 5];
  const b = [6, 7, 8, 9, 10];

  //配列の結合
  const c = [...a, ...b];
  
  //分割代入
  const [d, e, f] = a
  
  //rest構文
  const [g, h, ...i] = a
  
  
  console.log(...a); // 1 2 3 4 5
  console.log(c); // [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]
  console.log(d, e, f); // 1 2 3
  console.log(g, h, i); // 1 2 [ 3, 4, 5 ]
  
  
  //値の交換
  let [x,y,z] = [1,2,3]
  console.log(x,y,z); // 1 2 3
  
  [x, y, z] = [y, z, x];
  console.log(x, y, z); // 2 3 1
 

参照渡したくない場合

  const a = [1, 2];
  
  const b = a;
  const c = [...a];
  
  a[0] = 3;
  
  console.log(b); // [3, 2]
  console.log(c); // [1, 2]

配列操作のメソッド

2020-04-01_09h18_38.png

splice(開始する位置, 削除数 [, 追加する要素, ...])

オブジェクト操作


  const a = {c: 1, d: 2, e: 3};
  
  //オブジェクトの結合
  const b = {...a, f: 4, g: 5};
  
  //分割代入,存在しないキーを指定するとエラーになる
  const {c, d, ...h} = b;
  
  console.log(b); // { c: 1, d: 2, e: 3, f: 4, g: 5 }
  console.log(c, d, h); // 1 2 { e: 3, f: 4, g: 5 }
  
  //キーを取り出す方法
  const i = Object.keys(b);
  console.log(i); // [ 'c', 'd', 'e', 'f', 'g' ]
  
  //キーと値を表示
  for(let key of i) console.log(`key:${key} value:${b[key]}`);
  /*
  key:c value:1
  key:d value:2
  key:e value:3
  key:f value:4
  key:g value:5
  */
1
2
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
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?