JavaScript 提供了一个方法来测试变量类型。但是,其结果可能是令人困惑的 -- 比如,一个数组类型是 "object"。
当准备检测特定值的类型时,通常惯例是使用 typeof 运算符。
Example 2.40. 测试各种变量的类型
var myFunction = function() {
console.log('hello');
};
var myObject = {
foo : 'bar'
};
var myArray = [ 'a', 'b', 'c' ];
var myString = 'hello';
var myNumber = 3;
typeof myFunction; // 返回 'function'
typeof myObject; // 返回 'object'
typeof myArray; // returns 'object' -- careful!
typeof myString; // 返回 'string';
typeof myNumber; // 返回 'number'
typeof null; // returns 'object' -- careful!
if (myArray.push && myArray.slice && myArray.join) {
// 可能是个数组
// (这叫动态类型"duck typing")
}
if (Object.prototype.toString.call(myArray) === '[object Array]') {
// 定义一个数组!
// 这是一个被广泛验证过的可靠方法
// to 判断一个特殊值是不是一个数组。
}
jQuery 提供了实用方法来帮助你检测一个任意值的类型。这些内容将在后面涉及。
Copyright Rebecca Murphey, released under the Creative Commons Attribution-Share Alike 3.0 United States license.