JavaScriptではObjectを使用する.prototype.toStringは配列かどうかを判断する

1141 ワード

どうしてObjectを使うの?prototype.FunctionではなくtoStringprototype.toStringか他?これは彼らのtoString解釈と関係がある.以下はECMAにおけるObjectである.prototype.toStringの解釈:
 
  
Object.prototype.toString( )

When the toString method is called, the following steps are taken:
1. Get the [[Class]] property of this object.
2. Compute a string value by concatenating the three strings “[object “, Result (1), and “]”.
3. Return Result (2)


その過程は簡単に言えば、1、オブジェクトのクラス名(オブジェクトタイプ)を取得する.2、それから[object、取得したクラス名、]を組み合わせて返す.
ECMAではArrayについて次のように説明しています.
 
  
The [[Class]] property of the newly constructed object is set to “Array”.

配列を検出するには、次のコードを使用します.
 
  
function isArray(o) {   return Object.prototype.toString.call(o) === '[object Array]';  } 

この方式はinstanceofに存在するページ間問題も解決し,属性検出方式に存在する問題も解決し,実に妙技であり,良い解決策である.
このほか,この解決策はDate,Functionなどのタイプのオブジェクトを判断するためにも適用できる.
 
他にもいくつかの方法があります.
 
  
var arr = []; return arr instanceof Array; 

他にいい方法があれば貼ってもいいです.