Bitshift operator used for an object in Javascript

I have been trying to teach myself Javascript lately, and I notice several slightly bizarre syntax solutions used by different different authors. Usually I can understand them, but it puzzled me a little.

The author of the message here creates an empty object, a color that will contain a set of properties for each background color on the page. Each color property will have a value equal to the total area covered by that color. To do this, it uses the following syntax:

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

At this point, a property called the bgColor value may or may not be in the object. The purpose of the expression in parentheses seems to be to return the current total value, or 0 if this is the first time the color is displayed. My question is that this right shift operator is overloaded, and I was looking for the wrong name, or why does the right shift behave this way?

+4
source share
3 answers

The purpose of the expression in parentheses seems to be to return the current total value, or 0 if this is the first time the color is displayed. My question is that this right shift operator is overloaded, and I was looking for the wrong name, or why does the right shift behave this way?

(JavaScript ). , undefined >> 0 0, anyNumber >> 0 - anyNumber ( ). , undefined, >> 0 0. , 32 , >> 0 . ( , , 32 , wrapped, , , , .) , , ( , ).

:

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

... ( false >> 0 0), , NaN , nodeArea NaN non-number colors[bgColor] ({}, ), "" NaN.

+5

, if. bgColor, -

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

, 0, bgColor colors, undefined . , , undefined 0, if.

console.log(undefined >> 0);
# 0

, colors[bgColor] >> 0 0, bgColor , , .

+1

32- , Javascript 64- IIRC ( 53- ), 32- . , NodeArea.

, Number, NodeArea .

edit - TJ Crowder also makes another point that I tried to find from MDN but did not: the return value of the operation, if the property does not exist, is 0, thereby also setting the value). On the face of all his message makes a good point: P.

+1
source

Source: https://habr.com/ru/post/1548142/


All Articles