JavaScript 提供了一種方法來測試變量的類型。然而,其結果可能會讓人迷惑 - 例如,一個數組的類型是?`object`。
當試圖檢測一個特定值的類型時,常見的做法是使用?`typeof`?運算符。
~~~
// Testing the type of various variables.
var myFunction = function() {
console.log( "hello" );
};
var myObject = {
foo: "bar"
};
var myArray = [ "a", "b", "c" ];
var myString = "hello";
var myNumber = 3;
var myRegExp = /(\w+)\s(\w+)/;
typeof myFunction; // "function"
typeof myObject; // "object"
typeof myArray; // "object" -- Careful!
typeof myString; // "string"
typeof myNumber; // "number"
typeof null; // "object" -- Careful!
typeof undefined; // "undefined"
typeof meh; // "undefined" -- undefined variable.
typeof myRegExp; // "function" or "object" depending on environment.
if ( myArray.push && myArray.slice && myArray.join ) {
// probably an array (this is called "duck typing")
}
if ( Object.prototype.toString.call( myArray ) === "[object Array]" ) {
// Definitely an array!
// This is widely considered as the most robust way
// to determine if a specific value is an Array.
}
~~~