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?

JavaScript pop()関数:配列の最後の要素を削除する

0
Posted at

定義と使用方

pop()関数は、配列の最後の要素を削除(pop、つまり「ポンッ」と押し出すように)する関数です。

特徴

  • 配列の最後の要素を削除します。
  • 元の配列自体を直接変更します。
  • この動作によって配列の長さが1つ減ります。
  • 削除された要素を返します。

基本例

const arr = [1, 2, 3];

// 配列の最後の要素を削除します。
arr.pop();
console.log(arr); // 出力:[1, 2]

構文

arr.pop()

戻り値

pop()関数は、配列から削除された最後の要素の値を返します。
pop()関数で削除する要素がなく、配列が空の場合はundefinedが返されます。

const arr = [1, 2, 3];

// 配列の最後の要素を削除します。
const removedItem = arr.pop();
console.log(arr); // 出力:[1, 2]
console.log(removedItem); // 出力:3

// 配列が空の場合
const emptyArray = [];
const emptyArrayRemovedItem = emptyArray.pop(); // 削除する要素がなく、配列が空である

console.log(emptyArrayRemovedItem); // 出力:undefined

注意すべき点とさまざまな状況

# 戻り値

pop()関数は削除した要素を返します。返された値は変数に保存することができます。

const fruits = ["apple", "banana", "cherry"];
const removedFruit = fruits.pop();

console.log(removedFruit); // 出力:"cherry"

# 元の配列の変更と配列の長さ

pop()関数は元の配列を変更します。したがって、配列から要素を削除すると配列が変更され、配列の長さが短くなるという点を理解しておく必要があります。

const fruits = ["apple", "banana", "cherry"];
fruits.pop();

console.log(fruits.length); // 出力:2

# ループと併用して逆順に並べ替える

pop()関数とループを使用して、配列を逆順に並べ替えることができます。

const fruits = ["apple", "banana", "cherry"];

// 逆順に並べ替えるための空の配列を作成
const reversedFruits = [];

// 逆順に出力するためにループを使用
while (fruits.length > 0) {
    reversedFruits.push(fruits.pop());
}

// 逆順に並べ替えられた配列を出力
console.log(reversedFruits); // 出力:["cherry", "banana", "apple"]

参考資料

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?