当我执行下面的代码时,它打印“未定义”两次。 我预计它会引发错误,因为变量未定义,并且顶部还有 use strict' 语句。
'use strict';
var a;
console.log(typeof a);
console.log(typeof b);
谁能解释一下为什么它没有引发错误?
最佳答案
事实上,在 JavaScript 中 undefined
意味着变量尚未定义,所以基本上:
typeof a
返回undefined
,因为变量a
仅被声明但尚未初始化(没有为其分配任何值) .并且
typeof b
返回undefined
,因为变量b
尚未声明,因此尚未定义。
如果没有为变量分配任何值,它的类型就会为 undefined
,因为无法确定 as 类型。
因此,如果您检查 MDN typeof specification 你会看到:
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
.
示例:
您可以在示例部分中看到未定义的返回:
// Undefined
typeof undefined === 'undefined';
typeof declaredButUndefinedVariable === 'undefined';
typeof undeclaredVariable === 'undefined';
注意:
正如评论中所述,这仅与 JavaScript 语法有关,与 Nodejs 没有任何关系。
关于javascript - 理解 Javascript Typeof,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36594660/