gpt4 book ai didi

javascript - javascript中的 'in'关键字是什么意思?

转载 作者:搜寻专家 更新时间:2023-11-01 04:47:21 24 4
gpt4 key购买 nike

我找到了这段代码:

if (!("aa" in window)) {  
alert('oh my god');
var aa = 1;
}
alert("aa" in window);
alert(aa);

此代码第二个警报是警报 true,但是,第三个警报是“未定义”,并且“if”中的警报未运行。为什么?

我认为原因是in;它的作用是什么?

我在 Google 上搜索过,但一无所获,因为 Google 认为“在”这个词是“in”。是过滤词。

我们总是在循环中使用in,但是,坦率地说,我使用它但并不真正理解它。

最佳答案

这将测试 window 对象是否具有键为 "aa" 的属性(已填充或未填充)。

此运算符非常有用,因为即使值为 undefined 也能正常工作:

window.aa = undefined; // or just aa=undefined if you're in the global scope
console.log('aa' in window); // logs true

如果属性不可枚举,它也有效:

console.log('length' in []); // logs true

在您的情况下,可能没有 aa 值,但如果警报显示为 true,则该属性已添加到 window

MDN reference on in

请注意,for...in 语句的不同之处在于它并不真正使用 in 运算符,而是一种特定的构造。

MDN reference on for...in


编辑:对您编辑的问题的解释(与第一个问题非常不同):

您的困惑似乎源于您在 block 中声明了 var aa = 1;。您应该知道 JavaScript 中变量的作用域要么是全局作用域的函数,要么声明被提升。所以你的代码实际上等同于

var aa = undefined;
if (!("aa" in window)) { // aa is in window, so we don't enter here
alert('oh my god');
aa = 1;
}
alert("aa" in window); // yes, the property exists, it's true
alert(aa); // aa is still undefined

关于javascript - javascript中的 'in'关键字是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16831812/

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