gpt4 book ai didi

javascript - typeof 可以返回一个错误的值吗?

转载 作者:行者123 更新时间:2023-12-04 15:04:26 26 4
gpt4 key购买 nike

我偶然发现了 React 中一些有趣的代码。 Link to code

if (typeof data[Symbol.iterator]) { ... }

在我的理解中,typeof[data[Symbol.iterator]] 应该是真实的,因为 typeof 返回一个字符串。喜欢:

const obj = {}
if(typeof(obj.x)){
console.log("hello world");
}

给出“hello world” 因为即使是 typeof(undefined) => "undefined"=> truthy

tldr:typeof 是否有任何可能的错误结果?

最佳答案

如所述here :

ErrorsBefore ECMAScript 2015, typeof was always guaranteed to returna string for any operand it was supplied with. Even with undeclaredidentifiers, typeof will return 'undefined'. Using typeof could nevergenerate an error.

But with the addition of block-scoped let and Statements/const usingtypeof on let and const variables (or using typeof on a class) in ablock before they are declared will throw a ReferenceError. Blockscoped variables are in a "temporal dead zone" from the start of theblock until the initialization is processed, during which, it willthrow an error if accessed.

typeof undeclaredVariable === 'undefined';

typeof newLetVariable; // ReferenceError
typeof newConstVariable; // ReferenceError
typeof newClass; // ReferenceError

let newLetVariable;
const newConstVariable = 'hello';
class newClass{};

一般来说,typeof() 将返回一个字符串,因此如果单独检查一个条件,则它总是为真。如果你想检查一个变量并验证它是否未定义(或任何其他状态),你可以使用如下条件:typeof(undefinedvariable) == "undefined"

关于javascript - typeof 可以返回一个错误的值吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66422882/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com