本文介绍了在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,这与保留关键字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报价.

建议在文件的最顶部或函数内部声明"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]

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

10-18 21:30