理解Javascript Typeof [英] understanding Javascript Typeof
问题描述
当我执行下面的代码时,它会打印两次未定义".我原以为它会引发错误,因为未定义变量,并且顶部还有 use strict' 语句.
When I execute below code , it prints "undefined" two times. I was expecting that it would raise error since variable is not defined and also there is use strict' statement in the top.
'use strict';
var a;
console.log(typeof a);
console.log(typeof b);
谁能解释为什么它没有引发错误?
Can anyone explain why it is not raising an error ?
推荐答案
实际上在 JavaScript 中 undefined
意味着变量尚未定义,所以基本上:
In fact in JavaScript undefined
means that the variable isn't yet defined, so basically :
typeof a
返回undefined
因为变量a
仅声明但尚未初始化(没有分配给它的值).
typeof a
returnsundefined
because the variablea
was only declared but not initialized yet (there's no value assigned to it).
并且 typeof b
返回 undefined
因为变量 b
尚未声明,因此未定义.
And typeof b
returns undefined
because the variable b
is not yet declared, so isn't defined.
如果变量没有赋值,它的类型为 undefined
因为无法确定类型.
And if there's no value assigned to a variable, it gets the type undefined
because as type can't be determined.
因此,如果您查看 MDNtypeof 规范你会看到:
So if you check the MDN typeof specification you will see that :
typeof
运算符返回一个字符串,指示未计算的操作数的类型,如果您看到类型表,您可以看到 undefined
是一个原始类型,并且是typeof
的可能返回值.
The
typeof
operator returns a string indicating the type of the unevaluated operand, and if you see types table you can see thatundefined
is a primitive type and one of the possible return values oftypeof
.
示例:
您可以在示例部分看到未定义的返回:
And you can see in the Examples section, the undefined return:
//未定义
typeof undefined === 'undefined';
typeof undefined === 'undefined';
typeof DeclarationButUndefinedVariable === 'undefined';
typeof declaredButUndefinedVariable === 'undefined';
typeof undeclaredVariable === 'undefined';
typeof undeclaredVariable === 'undefined';
注意:
正如评论中所述,这仅与 JavaScript 语法有关,与 nodejs 无关.
这篇关于理解Javascript Typeof的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!