一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

Jquery typeof的使用方法详解

时间:2016-06-15 编辑:简简单单 来源:一聚教程网

ypeof语法: typeof([extension])

即typeof后边跟一个表达式,要不要括号都可以。它将返回一个字符串,表示表达式的类型,而表达式的类型只有六种可能:number、string、boolean、object、function、undefined

实际的类型可以参考微软的一份JScript帮助文档中的“JScript 的数据类型”,其中还有null,但null经过typeof返回的类型是object。而一个变量,如果没有赋值时,它的类型为undefined,但它值为null。

typeof的误用:

if (x == undefined) if (typeof(x) == undefined) 正确的应该是 if (typeof(x) == "undefined")

对比这两句话: //var x; if (typeof(x) == "undefined") alert("OK1"); if (x==null) alert("OK2");

有定义语句var x;时,两句都执行正常。 如果没有定义语句时,第一句没问题,第二句就提示'x'未定义

再对比这两句:

x=null; if (typeof(x) == "undefined") alert("OK1"); if (x==null) alert("OK2");

因此用typeof来检测变量是否有定义是最合适不过的了

以下把几种情况都列出来:

n=12.2;
alert("n=12.2:" + typeof n);

n="12.2";
alert("n=\"12.2\":" + typeof n);

n=false;
alert("n=false:" + typeof n);

n=[12, 11, 13];
alert("n=[12, 11, 13]:" + typeof n);
alert("n[1]:" + typeof n[1]);

obj=function (){var i=0; function show() { alert(i); }};
n=new obj();
alert("n=new obj():" + typeof n);

n=function () { alert("OK"); };
alert("n=function () { alert(\"OK\"); }:" + typeof n);

alert("nnnnnn:" + typeof nnnnnn);

alert("null:" + typeof null);

以typeof的误用有如下两种情况:

if (x == undefined)
if (typeof(x) == undefined)
正确的应该是
if (typeof(x) == "undefined")

对比这两句话:

//var x;
if (typeof(x) == "undefined") alert("OK1");
if (x==null) alert("OK2");

有定义语句var x;时,两句都执行正常。
如果没有定义语句时,第一句没问题,第二句就提示'x'未定义

再对比这两句:

x=null;
if (typeof(x) == "undefined") alert("OK1");
if (x==null) alert("OK2");

因此用typeof来检测变量是否有定义是最合适不过的了。返回到最原始的问题:
if (typeof window.jQuery == "undefined")
{
 var jQuery = ...
 ...
}

这段代码加上里面的程序体,就能够保证程序体只被执行一次,第二次执行时,

typeof window.jQuery就是"function"了。举例:有个文件,script引用写了两遍
1.htm








通过断点,我们可以看出对于jQuery的构建,只在第一次执行。

不过,我感到可惜的是,如果不同窗口,就要分别执行了。如以下两个文件:
1.htm





链接到第二个页面2.htm


2.htm





第二页面




jQuery的构建体就执行了两遍。

热门栏目