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】reverseメソッドの使い方

Posted at

#プログラミング勉強日記
2021年1月31日
昨日の記事でJavaScriptのsortメソッドの使い方についてまとめたが、今日はreverseメソッドを知ったのでreverseメソッドについて簡単にまとめる。

#reverseメソッドとは
 名前の通り、配列の要素を逆順に並び替える。対象となる配列そのものの要素が逆順に並び替えるので、戻り値としても並び替え終わった配列が返される。

使い方
配列名.reverse();

#使い方

let str = ["baseball", "soccer", "tennis", "swimming", "basketball"];
str.reverse();
 
console.log(str);
実行結果
["basketball", "swimming", "tennis", "soccer", "baseball"]

#注意点
 sortメソッド同様、元の配列を変更してしまう破壊的メソッドである。元の配列を残しておきたい場合には、sliceメソッドで配列のコピーを作成しておくといい。

let str = ["baseball", "soccer", "tennis", "swimming", "basketball"];
let str_copy = str.slice();
str.reverse();

console.log(str);
console.log(str_copy);
実行結果
["basketball", "swimming", "tennis", "soccer", "baseball"]
["baseball", "soccer", "tennis", "swimming", "basketball"]
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?