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 2022-04-07

用途

  • 配列の要素を削除したい時、要素を減らしたい時に使用する。

使用方法

shift

書き方
配列名.shift();

配列の先頭の要素を削除し、残りの要素を戻り値として返す。
配列が元から空だった場合は undefined を返す。
残っている要素についてはインデックスが1つずつ小さくなる。

var hoge = ["hoge1", "hoge2", "hoge3"];
hoge.shift();

console.log(hoge);
結果
["hoge2", "hoge3"]

console.log(hoge[0]);
結果
hoge2

console.log(hoge.shift()) // 削除した値を取得
結果
hoge1

配列の先頭の要素を削除し、残りの要素のインデックスが1つずつ小さくなった。

pop

書き方
配列名.pop();

配列の末尾の要素を削除し、残りの要素を戻り値として返す。
配列が元から空だった場合は undefined を返す。

var hoge = ["hoge1", "hoge2", "hoge3"];
hoge.pop();

console.log(hoge);
結果
["hoge1", "hoge2"]

console.log(hoge.pop()) // 削除した値を取得
結果
hoge3

配列の末尾の要素が削除された。

length

書き方
配列名.length = 指定したい数の数値;

「指定したい数の数値」の数だけ、要素を戻り値として返す。

var hoge = ["hoge1", "hoge2", "hoge3", "hoge4"];
hoge.length = 1;
console.log(hoge);
結果
["hoge1"]

hoge.length = 2;
console.log(hoge);
結果
["hoge1", "hoge2"]

hoge.length = 0;
console.log(hoge);
結果
[]

指定した数の要素が返される。(先頭から数える)

下記の記事を参考にしました。

0
0
1

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?