gpt4 book ai didi

javascript - 用于 Javascript 对象的位移运算符

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

我最近一直在尝试自学 Javascript,我注意到不同作者使用的几个稍微古怪的语法选项。通常我都能弄明白,但这个让我有点难过。

The author of the post here创建一个空对象 colors,它将包含页面中每种背景颜色的一组属性。每个颜色属性的值等于该颜色覆盖的总面积。为此,他使用以下语法:

// ...set or override it in the colors object,
// adding the current element area to the
// existing value.
colors[bgColor] = (colors[bgColor] >> 0) + nodeArea;

此时,对象中可能存在也可能不存在由 bgColor 的值命名的属性。括号中表达式的意图大概是返回运行总计,如果这是第一次看到颜色,则返回 0。我的问题是,这是不是右移运算符重载了,我正在搜索错误的名称,或者为什么右移运算符会这样?

最佳答案

The intent of the expression in the parenthesis is presumably to return the running total or 0 if this is the first time the color is seen. My question is, is this the right shift operator being overloaded and I'm searching for the wrong name, or why does the right shift behave this way?

它没有重载(JavaScript 没有运算符重载)。它依赖于 undefined >> 00anyNumber >> 0anyNumber 这一事实(警告跟随)。如果该属性尚不存在,查找它会产生 undefined,因此 >> 0 会将其转换为 0。如果属性 定义并且包含适合 32 位的整数,则 >> 0 返回该数字而不更改它。 (如果数字有小数部分,它会被 chop ,如果它不适合 32 位,它是 wrapped 如果我没看错的话,但我认为这不是编码器试图做的。 ) 因此,通过这样做,然后添加该区域,他们确实添加到运行总计中(如果尚不存在,则对其进行初始化)。

它主要是以下内容的简写版本:

if (colors[bgColor]) {
colors[bgColor] += nodeArea;
}
else {
colors[bgColor] = nodeArea;
}

...(因为任何错误值 >> 00)但具有附加功能,它将始终导致非 NaN 提供的数字 nodeArea 是一个非 NaN 数字,而 colors[bgColor] 有一些真实的非数字值({},例如),上面的“长”版本将生成字符串或 NaN

关于javascript - 用于 Javascript 对象的位移运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24707222/

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