1
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で躓いたこと

1
Last updated at Posted at 2022-08-22

typeofで配列の型を調べるとObjectが返ってきてしまう

まれに配列操作がうまくいかないことありますよね!
そんな時はtypeofを使って本当にデータの型があっているのかを確認したりします。
しかし、

let array = []
console.log(typeof array)
// object

と出力されます。あれどこの処理で変わってしまっているのかと判断してしまい、意味のないデバッグが始まりました。

その型が配列がどうか確かめたい時は、

let array = []
console.log(Array.isArray(array))
// true

としましょう

数字を持った配列のソートの仕方

let array = [1,2,3,4,5]
console.log(array.sort())
/// [1,2,3,4,5]
欲しいデータ
/// [5,4,3,2,1]

となってしまう。
なので、javascriptを使用して数字のソートを行いたい場合は、

const sortIndex = a.sort((a, b) => b - a)
console.log(sortIndex)
///
[5,4,3,2,1]が入力される
1
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
1
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?