> jQuery's .type()
方法:深入研究可变类型检测
JQuery提供了一个功能强大的函数.type()
,用于确定JavaScript变量的类型。 与JavaScript的typeof
运算符不同,.type()
>提供了更精确的结果,可以正确识别数组和空值。 它的实现利用toString()
和aclass2type
>对象进行综合类型检查。
>让我们检查.type()
函数的核心:
<code class="language-javascript">type: function( obj ) { return obj == null ? String( obj ) : class2type[ toString.call(obj) ] || "object"; },</code>
>该功能巧妙地使用了三元运算符。如果输入obj
为null
,则返回obj
对象,查找表映射对象类的字符串表示为其类型。如果在class2type
>中找不到匹配,则默认为“对象”。
class2type
>
class2type
<code class="language-javascript">var class2type = { "[object Array]": "array", "[object Boolean]": "boolean", "[object Date]": "date", "[object Function]": "function", "[object Number]": "number", "[object Object]": "object", "[object RegExp]": "regexp", "[object String]": "string" };</code>生成代表对象内部类的字符串,然后用作从
。
.type()
这是一个实用的例子:toString.call(obj)
class2type
<code class="language-javascript">var $forms = Array($('#register-form1'), $('#register-form2'), $('#register-form3')); console.log($.type($forms)); // Output: array</code>
>
.type()
以下常见问题解答有关jQuery的
运算符的差异。>
.type()
jquery.type()与JavaScript Typeof:
检查特定的数据类型:typeof
使用一个简单的比较:.type()
自定义对象类型:将返回用于创建自定义对象的构造函数函数的名称。if ($.type(variable) === "array") { ... }
>>和“ undefined” for .type()
返回jQuery对象的“对象”。使用JQuery的方法,例如>和.type()
>以获取更详细的信息。null
>
undefined
是案例敏感的;类型以小写返回。
> nan处理:.type()
>将NaN
视为“数字”。
数组与对象差异:不同,typeof
,.type()
,
jQuery版本兼容性:.type()
>可从JQuery 1.4.3开始。
功能类型检测:.type()
以上是jQuery获取可变类型的详细内容。更多信息请关注PHP中文网其他相关文章!