如何将javascript变量设置为未定义

如何将javascript变量设置为未定义,javascript,Javascript,鉴于: 鉴于: console.log(boo); this outputs undefined 定义boo并将其设置为1后,如何重置boo,使console.log输出未定义 谢谢这在Chrome Javascript控制台上运行: var boo = 1; console.log(boo); this outputs 1 您只需将未定义的值指定给变量: var boo = 1; console.log(boo); // prints 1 boo = undefined; console.

鉴于:

鉴于:

console.log(boo); this outputs undefined
定义boo并将其设置为1后,如何重置boo,使console.log输出未定义


谢谢

这在Chrome Javascript控制台上运行:

var boo = 1;
console.log(boo); this outputs 1

您只需将未定义的值指定给变量:

var boo = 1;
console.log(boo); // prints 1
boo = undefined;
console.log(boo); // now undefined
或者,您可以使用
delete
操作符删除变量:

boo = undefined;

删除boo

不要使用
var boo=undefined
。undefined只是一个变量,如果有人设置了
undefined=“hello”
,那么您将在任何地方都能看到hello:)

编辑:

null与undefined不同。已删除该位。

解决方案 要可靠地将变量
boo
设置为
undefined
,请使用带有空
返回表达式的函数:

delete boo;
执行这行代码后,
typeof(boo)
计算结果为
'undefined'
,无论
undefined
全局属性是否已设置为另一个值。例如:

boo = (function () { return; })();
编辑但也可参见@Colin's

参考文献 早在ECMAScript 1中,这种行为就是标准的。相关规范部分规定:

语法

返回
[no LineTerminator here]表达式

语义

return
语句导致函数停止执行并向调用方返回值。如果省略表达式,则返回值为未定义

要查看原始规格,请参阅:

附录 为了完整起见,我根据其他回复者给出的答案和评论,附上了对该问题备选方法的简要总结,以及对这些方法的反对意见

1.将
undefined
分配给
boo
虽然直接将
undefined
赋值给
boo
比较简单,
undefined
不是保留字,而是由任意值(如数字或字符串)赋值

2.删除
boo

删除
boo
会完全删除
boo
的定义,而不是为其赋值
undefined
,即使
boo
是全局属性。

使用
void
操作符。它将对其表达式求值,然后返回
undefined
。习惯用法是使用
void 0
将变量分配给
未定义的

delete boo; // not recommended

此处了解更多信息:

您不能
删除boo
,它是一个变量。只有当变量在全局范围内,即使在IE中不起作用,并且在严格模式下抛出错误时,它才起作用。请注意,这可能不适用于所有JavaScript运行时环境。我在Node.js中尝试了这个,但没有成功。Esailija是正确的。从:“
delete
仅对对象的属性有效。它对变量或函数名无效。”关于附录项目1:从:“
undefined
根据ECMAScript 5规范,在现代浏览器(JavaScript 1.8.5/Firefox 4+)中是不可配置、不可写的属性。”So
boo=未定义
在“现代浏览器”中是安全的,因为
未定义的
不能被覆盖。return语句不是多余的吗?这对我很有用:
\u foo=(函数(){})()@AndreschSerj,这对我也有用。return语句是多余的。我的IDE也对此表示不满:)请参见Colin的简单解决方案。只是不要这样做。空是一个更好的选择。@coldtree请将您接受的答案更改为gooseberry的答案Colin的答案也很好:
undefined = 'hello';
var boo = 1;
console.log(boo); // outputs '1'
boo = (function () { return; })();
console.log(boo); // outputs 'undefined'
console.log(undefined); // outputs 'hello'
boo = undefined; // not recommended
delete boo; // not recommended
var boo = 1; // boo is 1
boo = void 0; // boo is now undefined