假设:
console.log(boo); this outputs undefined
鉴于:
var boo = 1;
console.log(boo); this outputs 1
在定义boo并设置为1后,如何重置boo,以便console.log输出undefined?
由于
答案 0 :(得分:44)
要将变量boo
可靠地设置为undefined
,请使用空return
表达式的函数:
boo = (function () { return; })();
执行此行代码后,typeof(boo)
计算结果为'undefined'
,无论undefined
全局属性是否已设置为其他值。例如:
undefined = 'hello';
var boo = 1;
console.log(boo); // outputs '1'
boo = (function () { return; })();
console.log(boo); // outputs 'undefined'
console.log(undefined); // outputs 'hello'
编辑但请参阅@Colin的simpler solution!
此行为是ECMAScript 1的标准。相关规范部分说明:
<强>语法强>
return
[no LineTerminator 此处] 表达式;<强>语义强>
return
语句会导致函数停止执行并将值返回给调用者。如果省略 Expression ,则返回值为undefined
。
要查看原始规格,请参阅:
为了完整起见,我根据其他响应者给出的答案和评论,附上了对此问题的替代方法的简要概述,以及对这些方法的反对意见。
undefined
分配给boo
boo = undefined; // not recommended
虽然直接将undefined
分配给boo
更为简单,但undefined
不是保留字,could be replaced是任意值,例如数字或字符串。
boo
delete boo; // not recommended
删除boo
会完全删除boo
的定义,而不是为其分配值undefined
,如果boo
是全局属性,则会only works
答案 1 :(得分:27)
使用void
运算符。它将评估它的表达式,然后返回undefined
。使用void 0
将变量分配给undefined
var boo = 1; // boo is 1
boo = void 0; // boo is now undefined
点击此处了解详情:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/void
答案 2 :(得分:14)
您可以简单地为变量赋值undefined:
boo = undefined;
或者,您可以使用delete
运算符删除变量:
delete boo;
答案 3 :(得分:10)
delete boo
请勿使用var boo = undefined
。 undefined只是一个变量,如果有人设置undefined = "hello"
,那么你将会到处打招呼:)
修改强>
null与undefined不同。删除了那一点。
答案 4 :(得分:2)
这适用于Chrome Javascript控制台:
delete(boo)
答案 5 :(得分:1)
var boo = 1;
console.log(boo); // prints 1
boo = undefined;
console.log(boo); // now undefined