在javascript中为undefined赋值 [英] Assigning value to undefined in javascript

查看:1042
本文介绍了在javascript中为undefined赋值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用JavaScript编写一些代码.当我不小心遇到这个问题时.

I was writing some code in javascript. When I accidentally came across this.

undefined = 'some value' //does not give any error

true = 'some value';   //gives error

null = 'some value';   //gives error

第一个语句有效,而另两个无效.据我所知,undefined,true和null都是可以分配给某个变量的值,因此所有这些都应该是无效的语句.

how is it that first statement is valid whereas the other two are invalid. From what I know both undefined, true and null are values you can assign to some variable, so all these should be invalid statements.

推荐答案

来自 MDN :

undefined是全局对象的属性;即它是一个变量 在全球范围内. undefined的初始值为原始值 undefined.

undefined is a property of the global object; i.e., it is a variable in global scope. The initial value of undefined is the primitive value undefined.

因此,您可以将值分配给undefined,这与保留关键字truenull不同.请注意,NaN也是这种情况,它也不是保留关键字,因此,您可以为其分配任何值.

Hence, you can assign the value to undefined unlike true and null which are reserved keywords. Note that this is the same case with NaN as well which is again not a reserved keyword and hence, you can assign any value to it.

只需添加更多内容,即使您为undefined分配了一个值也没关系,因为它是只读属性,因此不会对其进行写入.

Just to add more to this, it doesn't matter even if you are assigning a value to undefined, it will not write to it as it is a readonly property.

再次从MDN报价.

在现代浏览器(JavaScript 1.8.5/Firefox 4+)中,undefined是 根据ECMAScript 5的不可配置,不可写属性 规格.即使不是这种情况,也请避免覆盖它.

In modern browsers (JavaScript 1.8.5 / Firefox 4+), undefined is a non-configurable, non-writable property per the ECMAScript 5 specification. Even when this is not the case, avoid overriding it.

建议在文件的最顶部或函数内部声明"use strict",以在JavaScript中使用严格模式以避免此类情况.使用类似的东西

Prefer using strict-mode in your JavaScript by declaring "use strict" at the very top of the file or inside a function to avoid such things. Using something like

"use strict";
undefined = 'test'; //will raise an error, refer to [1]

[1] VM1082:2未捕获的TypeError:无法分配为读取 对象#"的唯一属性未定义"

[1] VM1082:2 Uncaught TypeError: Cannot assign to read only property 'undefined' of object '#'

这篇关于在javascript中为undefined赋值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆