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?

【JS】spliceの個人メモ

Last updated at Posted at 2024-12-04

配列の要素を削除・置換してくれるから個人メモ

  • spliceは自身を更新する関数。なので、裏側でimmerを使っているredux-toolkitのreducerなんかで使う。
  • 第1引数:index
  • 第2引数:置換数
  • 第3引数以降:置換後文字列。未指定の場合、削除。
const months = ["A", "B", "C", "D"];

// 0番目の要素を★に置換 → ["★","B","C","D"]
months.splice(0, 1, "");

// 最後の要素を★に置換 → ["A","B","C","★"]
months.splice(-1, 1, "");

// 1番目から要素2つ分を★に置換 → ["A","★","★","D"]
months.splice(1, 2, "", "");

// 第2引数の数値と、第3引数以降の数を合わせないと、要素数が増減する
// ['A', '★', 'D']←要素2つ分置換(第二引数の値)となっているが、
// 第3引数しかないため、元の2番目の要素だったCが削除された
months.splice(1, 2, "");


// 0番目の要素を削除 → ["B","C","D"]
months.splice(0, 1);


// 0番目から要素2つ分を削除 → ["C","D"]
months.splice(0, 2);


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?