2
1

More than 1 year has passed since last update.

JS配列にあれば削除なければ追加

Last updated at Posted at 2022-08-03

コード

live demo

const arr = [1,2,3,4]
const x = 5

// indexOf()による判断
const index = arr.indexOf(x);
// index < 0: なければ,追加
// index >= 0: ある,削除
index < 0 ? arr.push(x) : arr.splice(index, 1)

console.log(arr)
// [1,2,3,4,5]
2
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
2
1