[JavaScript General] データ型とその判定
memo.
[markdown]
## データ型
> [データ構造 – JavaScript | MDN](https://developer.mozilla.org/ja/docs/Web/JavaScript/Data_structures)
最新の ECMAScript 標準仕様では 7 つのデータ型が定義されています。
– 6 種類のプリミティブデータ型:
– Boolean
– Null
– Undefined
– Number
– String
– Symbol (ECMAScript 6 の新データ型)
– Object
## 真偽値での判定
`if (値)` で以下が返ってくる。
> [#07 真偽値と三項演算子を使おう | JavaScript入門 – プログラミングならドットインストール](http://dotinstall.com/lessons/basic_javascript_v2/26707)
– String … 空文字(`”`)以外だったら `true`
– Number … `0` か `NaN` 以外だったら `true`
– Boolean … そのまま `true`, `false`
– Object … `null` 以外だったら `true`
– undefined, null … ともに `false`
## Object の判定
ひとくちに Object といっても、いろいろある。
例えば `getElementById()` や `getElementsByClassName()` とした場合に返ってくる値に応じて、処理を分けたいと思ったけれども、そもそもどう分けるべきなのか。
### typeof 演算子では判別できない
typeof 演算子では、すべて object が返ってくるので判定できない。
“`javascript
const element = document.getElementById(‘test’);
const elements = document.getElementsByClassName(‘hover’);
const elements2 = document.getElementsByTagName(‘a’);
console.log(typeof element); // object
console.log(typeof elements); // object
console.log(typeof elements2); // object
“`
> * [typeof 演算子 – JavaScript | MDN](https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Operators/typeof)
> * [文法とデータ型 – JavaScript | MDN](https://developer.mozilla.org/ja/docs/Web/JavaScript/Guide/Grammar_and_types#Data_structures_and_types)
### Object.prototype.toString.call() を使う
それぞれ何が返ってくるのかを調べると、以下のようである。
`HTMLCollection` で判定すれば良さそうだ。
> * [document.getElementById() – Web APIs | MDN](https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementById)
>
> element is a reference to an Element object, or null if an element with the specified ID is not in the document.
>
> * [Document.getElementsByClassName() – Web APIs | MDN](https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName)
>
> elements is a live HTMLCollection of found elements.
>
> * [Document.getElementsByTagName() – Web APIs | MDN](https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByTagName)
>
> elements is a live HTMLCollection (but see the note below) of found elements in the order they appear in the tree.
“`javascript
if (Object.prototype.toString.call(elements) === “[object HTMLCollection]”) {
処理
}
“`
> * [How to detect HTMLCollection/NodeList in JavaScript? – Stack Overflow](http://stackoverflow.com/questions/7238177/how-to-detect-htmlcollection-nodelist-in-javascript)
> * [JavaScriptで型判定いろいろ – Cheese Pie](http://d.hatena.ne.jp/cheesepie/20091122/1258897939)
> * [JavaScriptの「型」の判定について – Qiita](http://qiita.com/south37/items/c8d20a069fcbfe4fce85)
See the Pen JavaScript: how to detect data types by DriftwoodJP (@DriftwoodJP) on CodePen.
## 補遺
> * [NaNはNot a NumberだけどNumber型である話 | Web Scratch](http://efcl.info/2016/09/06/nan/)
[/markdown]