LoginSignup
0
0

More than 3 years have passed since last update.

【javascript, TypeScript】任意の数字を配列から削除する

Last updated at Posted at 2020-05-31

はじめに

この記事では、
『配列の中に、任意の数字があるかどうかを判断し、ある場合は配列から消す処理』
を紹介しています。

【splice】という、関数を使用しました。

下記のページを参考にしています。
参考ページ

プログラム

const array = [0, 1, 2, 3, 4, 5];

// 削除したい数字
const deleteNum = 2;

// 配列の中に【任意の数字】が何番目にあるかを数字で返す (ない場合 -1 を返す)
const index = array.indexOf(deleteNum);

// 配列の中に【任意の数字】があった場合
if (index > -1) {
 // 配列の先頭から【index】番目の数字を削除
 array.splice(index, 1);
}

// [0, 1, 3, 4, 5]
console.log(array);
0
0
2

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