我对JavaScript的undefined和null值有点困惑。
if (!testvar)实际上做什么?它是否测试为undefined和null或只是undefined?
一旦一个变量被定义,我可以把它清除回未定义(因此删除变量)?
我可以传递undefined作为参数吗?例如:
function test(var1, var2, var3) {
}
test("value1", undefined, "value2");
我对JavaScript的undefined和null值有点困惑。
if (!testvar)实际上做什么?它是否测试为undefined和null或只是undefined?
一旦一个变量被定义,我可以把它清除回未定义(因此删除变量)?
我可以传递undefined作为参数吗?例如:
function test(var1, var2, var3) {
}
test("value1", undefined, "value2");
当前回答
我对Javascript的undefined和null有点困惑。
null的行为通常类似于其他脚本语言的带外‘null’、‘nil’或‘None’对象的概念。
另一方面,undefined是一个奇怪的JavaScript怪癖。它是一个表示带外值的单例对象,本质上是第二个相似但不同的null。它出现了:
When you call a function with fewer arguments than the arguments list in the function statement lists, the unpassed arguments are set to undefined. You can test for that with eg.: function dosomething(arg1, arg2) { if (arg2===undefined) arg2= DEFAULT_VALUE_FOR_ARG2; ... } With this method you can't tell the difference between dosomething(1) and dosomething(1, undefined); arg2 will be the same value in both. If you need to tell the difference you can look at arguments.length, but doing optional arguments like that isn't generally very readable. When a function has no return value;, it returns undefined. There's generally no need to use such a return result. When you declare a variable by having a var a statement in a block, but haven't yet assigned a value to it, it is undefined. Again, you shouldn't really ever need to rely on that. The spooky typeof operator returns 'undefined' when its operand is a simple variable that does not exist, instead of throwing an error as would normally happen if you tried to refer to it. (You can also give it a simple variable wrapped in parentheses, but not a full expression involving a non-existant variable.) Not much use for that, either. This is the controversial one. When you access a property of an object which doesn't exist, you don't immediately get an error like in every other language. Instead you get an undefined object. (And then when you try to use that undefined object later on in the script it'll go wrong in a weird way that's much more difficult to track down than if JavaScript had just thrown an error straight away.) This is often used to check for the existence of properties: if (o.prop!==undefined) // or often as truthiness test, if (o.prop) ...do something... However, because you can assign undefined like any other value: o.prop= undefined; that doesn't actually detect whether the property is there reliably. Better to use the in operator, which wasn't in the original Netscape version of JavaScript, but is available everywhere now: if ('prop' in o) ...
总之,undefined是javascript特有的混乱,这让所有人都感到困惑。除了可选函数参数之外,JS没有其他更优雅的机制,应该避免使用undefined。它不应该成为语言的一部分;null对于(2)和(3)来说可以很好地工作,(4)是一个错误的特性,因为在一开始JavaScript没有异常。
if (!testvar)实际上做什么?它是否测试为undefined和null或只是undefined?
这样的“真实性”测试检查假,未定义,null, 0, NaN和空字符串。但在这种情况下,它确实是没有定义的。在我看来,它应该更明确地说,如果(testvar!==undefined)。
一旦一个变量被定义,我可以把它清除回未定义(因此删除变量)。
你当然可以给它赋值为undefined,但这不会删除变量。只有delete对象。属性操作符实际上删除了一些东西。
Delete实际上指的是属性,而不是变量本身。浏览器允许你直接删除变量,但这不是一个好主意,在ECMAScript第五版的严格模式下也行不通。如果你想释放对某个东西的引用,这样它就可以被垃圾收集,更常见的说法是variable= null。
我可以传递undefined作为参数吗?
Yes.
其他回答
如何在命令行中设置一个变量为undefined:
在Ubuntu 12.10上的Java自带的js javascript命令行终端中将一个变量设置为undefined。
el@defiant ~ $ js
js> typeof boo
"undefined"
js> boo
typein:2: ReferenceError: boo is not defined
js> boo=5
5
js> typeof boo
"number"
js> delete(boo)
true
js> typeof boo
"undefined"
js> boo
typein:7: ReferenceError: boo is not defined
如果你在javascript中设置一个变量为undefined:
把这个放到myjs.html中:
<html>
<body>
<script type="text/JavaScript">
document.write("aliens: " + aliens);
document.write("typeof aliens: " + (typeof aliens));
var aliens = "scramble the nimitz";
document.write("found some aliens: " + (typeof aliens));
document.write("not sayings its aliens but... " + aliens);
aliens = undefined;
document.write("aliens deleted");
document.write("typeof aliens: " + (typeof aliens));
document.write("you sure they are gone? " + aliens);
</script>
</body>
</html>
输出如下:
aliens: undefined
typeof aliens: undefined
found some aliens: string
not sayings its aliens but... scramble the nimitz
aliens deleted
typeof aliens: undefined
you sure they are gone? undefined
警告!当你把你的变量设置为undefined时,你就是在把你的变量设置为另一个变量。如果一些鬼鬼祟祟的人运行undefined = 'rm -rf /';然后,无论何时将变量设置为undefined,都将收到该值。
您可能想知道我如何在开始时输出未定义的值异形,并使其仍然运行。这是因为javascript提升:http://www.adequatelygood.com/JavaScript-Scoping-and-Hoisting.html
要回答您的第一个问题,not操作符(!)将强制将给定的值转换为布尔值。因此null, 0, false, NaN和“”(空字符串)都将显示为false。
是的,你可以,因为未定义定义为未定义。
console.log(
/*global.*/undefined === window['undefined'] &&
/*global.*/undefined === (function(){})() &&
window['undefined'] === (function(){})()
) //true
你的情况:
test("value1", undefined, "value2")
你也可以创建自己的未定义变量:
Object.defineProperty(this, 'u', {value : undefined});
console.log(u); //undefined
只是为了好玩,这里有一种相当安全的方法将“未赋值”赋值给变量。为了产生碰撞,需要有人在Object原型中添加与随机生成的字符串完全相同的名称。我确信随机字符串生成器可以得到改进,但我只是从这个问题中取了一个:在JavaScript中生成随机字符串/字符
这是通过创建一个新对象并尝试访问一个随机生成的名称在它上的属性,我们假设不存在,因此将有undefined的值。
function GenerateRandomString() {
var text = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for (var i = 0; i < 50; i++)
text += possible.charAt(Math.floor(Math.random() * possible.length));
return text;
}
var myVar = {}[GenerateRandomString()];
你不能(不应该?)将任何东西定义为未定义的,因为变量将不再是未定义的——你只是将它定义为某个东西。
不能(不应该?)将undefined传递给函数。如果你想传递一个空值,使用null代替。
语句if(!testvar)检查布尔值为true/false,这个语句测试testvar的结果是否为false。根据定义,null和undefined既不应该被赋值为true也不应该被赋值为false,但是JavaScript将null赋值为false,如果您尝试求值一个undefined变量,则会给出一个错误。
要正确地测试undefined或null,请使用以下命令:
if(typeof(testvar) === "undefined") { ... }
if(testvar === null) { ... }