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

JavaScriptの配列操作で使える構文をまとめてみた。

Last updated at Posted at 2021-06-24

JSの構文をいくつか備忘録としてまとめてみました。

配列基礎メソッド

先頭・末尾の削除

push

末尾に追加

const array = [1, 2, 3]
array.push(4)
=>[1, 2, 3, 4]

unshift

先頭に追加

const array = [1, 2, 3]
array.unshift(0)
=>[0, 1, 2, 3]

pop

末尾の要素を削除

const array = [1, 2, 3]
array.pop(3)
=>[1, 2]

shift

先頭の要素を削除

const array = [1, 2, 3]
array.shift(1)
=>[2, 3]

途中の要素に対して追加や削除をする

splice

配列.splice(インデックス番号, 0, 挿入する要素) // 挿入
配列.splice(インデックス番号, 1) // 削除(抽出)
const array = [1, 2, 3];

array.splice(0, 0, 'B')
=> [ 'B', 1, 2, 3 ]

array.splice(3, 1)
=>[ 'B', 1, 2 ]

##分割代入

const profile = {
  name: "aa",
  age: 24,
};

//オブジェクトから指定のプロパティを抜き出せる
const { name, age } = profile;
const message2 = `名前は${name}です。年齢は${age}歳です。`;
console.log(message2);
=> "名前はaaです。年齢は24歳です。"

###配列の分割代入

const profile = ['aa',24];

//配列の場合順番で格納される
const [name, age] = profile

const message3 = `名前は${name}です。年齢は${age}歳です。`

console.log(message3);
=> "名前はaaです。年齢は24歳です。"

##スプレッド構文

配列の展開

const arr = [1, 2];
console.log(arr);
console.log(...arr);

=>[ 1, 2 ]
=> 1 2

配列をまとめる

const arr = [1,2,3,4,5];
//1,2以外の数値をまとめて格納する
const [num1,num2, ...arr2] = arr;

console.log(num1);
console.log(num2);
console.log(arr2);
=> 1
=> 2
=>[ 3, 4, 5 ]

配列の結合

const arr = [10, 20];
const arr2 = [30, 40];

const arr3 = [...arr, ...arr2];

console.log(arr3);
=> [10, 20, 30, 40]

配列のコピー

const arr1 = [10, 20];
const arr2 = [30, 40];
const arr3 = [...arr1];

console.log(arr3);
=>[ 10, 20 ]

コピー時の参照問題

####イコールを使ってコピーすると元の配列も影響を受ける

const arr = [10, 20];

const arr2 = arr;
arr2[0] = 100;
console.log(arr);
console.log(arr2);

=>[ 100, 20 ]
=>[ 100, 20 ]

####スプレッド構文を使ってコピーすると元の配列は影響を受けない

const arr = [10, 20];
const arr2 = [...arr];
arr2[0] = 100;
console.log(arr);
console.log(arr2);

=> [100, 20]
=> [10, 20]

##map
####新しい配列を生成する

const nameArr = ["aa", "bb", "cc"];
const nameArr2 = nameArr.map(name => name);
console.log(nameArr2);

=> ["aa", "bb", "cc"]

####ループ処理

const nameArr = ["aa", "bb", "cc"];
nameArr.map( name => console.log(name));

=> aa
=> bb
=> cc

##filter
####ある条件に一致したものを返却して、新しい配列を生成する

const numArr = [1, 2, 3, 4, 5];
const newNumArr = numArr.filter(num => num % 2 === 1);
console.log(newNumArr);

=> [1, 3, 5]
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?