<html>
<head>
<title>JS</title>
<script type="text/javascript">
function test1()
{
//接着上一讲继续
//请大家猜测一下下面的结果是什么?
alert(typeof(typeof a));
/*
答案是string,你猜对了吗?你是不是认为结果是undefined
typeof a的结果是undefined,是Undefined类型的字面量。
所以我们可以得出个结论Undefined类型的字面量undefined是一个string类型的字符串,这个说法对吗?
现在看来可能对,但是我要告诉你这是不对的。
之所以结果是string是因为typeof函数的返回值是string类型的而不是上面所说的那个结论。
*/
}
function test2()
{
alert(typeof undefined);
/*
这是上一讲中的第一个,现在我们来思考一下下面的问题:
其中的undefined是Undefined类型的字面量还是只是一个名为undefined的变量?
我们到底能不能直接使用Undefined类型的字面量?
*/
}
/*
现在大家不会晕了吧,呵呵。
在开始推翻上面错误结论,解释为什么之前咱们先来搞清楚JavaScript的
一个基础知识点。看test3(),test4();
*/
function test3()
{
alert(a=="123");
//alert(a+1);
}
function test4()
{
var a;
alert(a>="123");
alert(a+1);
}
/*
test3()的结果是报错:变量a没有定义
test4()的结果是false;
通过比较上面两个函数的结果可以得出:
若一个变量没有声明直接使用,我这里说的使用是指对他进行加减乘除或和别的量
进行比较时就会报错。如果声明了就不会报错。
*/
/*
好,记住这个结论,我们利用这个结论来解释我们前面的疑问。
*/
/*
typeof undefined中的undefined是Undefined类型的字面量还是只是一个名为undefined的变量?
*/
function test5()
{
alert(undefined==a);
alert(a==undefined);
/*
运行结果是报错,上面两个报的错相同都是"a"没有定义。
这就说明了其中的undefined是Undefined类型的字面量,是可以直接拿来使用的。
*/
}
/*
错误结论:
Undefined类型的字面量undefined是一个string类型的字符串
*/
function test6()
{
alert(undefined=="undefined");
/*
上面的结果为false
证明了上述结论是错误的,undefined就是Undefined类型,而不是字符串类型。
*/
}
function test7()
{
alert(undefined==undefineD);
alert(undefineD==undefined);
/*
两个都是报错说undefineD未定义
用这个例子我想说明的是只有undefined是Undefined类型的字面量,其他类似的都是
普通的变量。
*/
}
</script>
</head>
<body>
<input type="button" onclick="test7()" value="Click">
</body>
</html>
关于Undefined类型字面量undefined的小小研究(2)
最新推荐文章于 2019-11-25 15:09:00 发布