"JavaScript Advanced Program Design" Reading notes---operation selector

Source: Internet
Author: User
Tags bitwise bitwise operators

Unary operator
An operator that can manipulate only one value is called a unary operator. The unary operator is the simplest operator in ECMAScript.

1. Increment and decrement operators
The increment and decrement operators draw directly from C, and each has two versions: front-and rear-mounted. As the name implies, the predecessor should precede the variable to be manipulated, and the latter should precede the variable to be manipulated. Therefore, when you use the Prepend increment operator to add 1 o'clock to a value, place the two plus sign (+ +) before the numeric variable, as follows:

var age = 29;
++age;

In this example, the pre-increment operator turns the value of age to 30 (29 plus 1). In fact, performing this predecessor increment operation is the same as doing the following:
var age = 29;
Age = age + 1;

The method of performing a pre-decrement operation is similar, and the result is subtracted from a value of 1. With the predecessor decrement operator, place the two minus sign (--) in front of the corresponding variable, as follows:
var age = 29;
--age;
In this way, the value of the age variable is reduced to 28 (minus 1 from 29).
When you perform a pre-increment and decrement operation, the value of the variable is changed before the statement is evaluated. (In the field of computer science, this is often referred to as a secondary effect.) Take a look at the example below.

var age = 29;
var anotherage =--age + 2;
alert (age); Output 28
alert (anotherage); Output 30

In this example, the initial value of the variable anotherage equals the value of the age of the variable before the decrement is added by 2. Because the subtraction operation was performed first, the value of age became 28, so the result of adding 2 was 30.
Because the pre-increment and decrement operations are equal to the precedence of the execution statements, the entire statement is evaluated from left to right. Let's look at an example:
var num1 = 2;
var num2 = 20;
var num3 =--num1 + num2; equals 21
var num4 = num1 + num2; equals 21

Here, num3 is equal to 21 because NUM1 minus 1 before adding to num2. The variable num4 is also equal to 21 because the corresponding addition operation uses the value NUM1 minus 1.
The syntax of the post-increment and decrement operators is constant (still the + + and--), except that it is placed behind the variable instead of the previous one.
There is a very important difference between post increment and decrement and pre-increment and decrement, that is, increment and decrement operations are performed after the statement that contains them is evaluated. This difference is not a problem in some cases, for example:
var age = 29;
age++;
Placing the increment operator behind a variable does not change the result of the statement, because incrementing is the only action for this statement. However, these differences are obvious when other actions are included in the statement. Take a look at the following example:
var num1 = 2;
var num2 = 20;
var num3 = num1--+ num2; equals 22
var num4 = num1 + num2; equals 21

Here, you can see the difference just by changing the forward decrement to a post-decrement. In the preceding example, num3 and num4 are equal to 21. In this case, num3 equals 22,num4 equals 21. The difference is rooted in the fact that the NUM3 is calculated using the original value of NUM1 (2) to complete the addition calculation, while the NUM4 uses the descending value (1).
All of these 4 operators apply to any value, that is, they apply not only to integers, but also to strings, Boolean values, floating-point values, and objects. The increment and decrement operators follow the following rules when applied to different values.
? When applied to a string that contains a valid numeric character, it is first converted to a numeric value, and then the operation with the addition minus 1 is performed. The string variable becomes a numeric variable.
? When applied to a string that does not contain a valid numeric character, sets the value of the variable to Nan (which is discussed in detail in the 4th chapter). The string variable becomes a numeric variable.
? When applied to a Boolean value of false, first convert it to 0 and then perform a plus minus 1 operation. A Boolean variable becomes a numeric variable.
? When applied to a Boolean value of true, first convert it to 1 and then perform a plus minus 1 operation. A Boolean variable becomes a numeric variable.
? When applied to floating-point values, performs a plus minus 1 operation.
? When applied to an object, the object's valueof () method is called first (discussed in detail in the 5th chapter) to get a value that can be manipulated. The aforementioned rules are then applied to the value. If the result is Nan, the aforementioned rule is applied after the ToString () method is called. The object variable becomes a numeric variable.
The following example shows some of the rules above:

var S1 = "2";
var s2 = "Z";
var B = false;
var f = 1.1;
var o = {
Valueof:function () {
return-1;
}
};
s1++; The value becomes the number 3
s2++; Value becomes Nan
b++; The value becomes the number 1
f--; Value becomes 0.10000000000000009 (due to floating-point rounding errors)
o--; Value becomes numeric-2

2. Unary Plus and minus operators

The vast majority of developers are not unfamiliar with unary plus and minus operators, and the two ECMAScript operators work exactly the same as in the math book. The unary plus operator is represented by a plus sign (+), preceded by a number, and has no effect on the value, as shown in the following example:
var num = 25;
num = +num; is still 25
However, when a unary plus operator is applied to a non-numeric value, the operator performs a transformation like the number () transformation function.
In other words, the Boolean value false and True will be converted to 0 and 1, and the string value will be parsed according to a special set of rules, and the object is to call their valueof () and (or) toString () method before converting the resulting value.
The following example shows the result of applying a unary plus operator to different data types:
var S1 = "01";
var s2 = "1.1";
var s3 = "Z";
var B = false;
var f = 1.1;
var o = {
Valueof:function () {
return-1;
}
};
S1 = +s1; The value becomes the number 1
s2 = +s2; The value becomes the number 1.1
s3 = +S3; Value becomes Nan
b = +b; The value becomes the number 0
f = +f; Value is unchanged, still 1.1
o = +o; Value becomes numeric-1

The unary minus operator is primarily used to represent negative numbers, such as converting 1 to 1. The following example illustrates this simple conversion process:
var num = 25;
num =-num; It becomes-25

When a unary subtraction operator is applied to a value, the value becomes negative (as shown in the example above). When applied to a non-numeric value, the unary minus operator follows the same rule as the unary plus operator, and finally converts the resulting value to a negative number, as shown in the following example:
var S1 = "01";
var s2 = "1.1";
var s3 = "Z";
var B = false;
var f = 1.1;
var o = {
Valueof:function () {
return-1;
}
};
S1 =-s1; Value becomes a number-1
s2 =-s2; Value becomes a number-1.1
s3 =-S3; The value becomes Nan
b =-C; The value becomes the number 0
f =-F; It becomes-1.1
o =-O; The value becomes the number 1

Unary plus and minus operators are primarily used for basic arithmetic operations, and can be used to transform data types as shown in the previous example.

Bitwise operators

Bitwise operators are used to manipulate values at the most basic level, that is, by the bits in memory that represent the values.

1. Bitwise non (NOT)
A bitwise non-operator is represented by a wavy line (~), and the result of performing a bitwise non is the inverse of the value returned. Bitwise is not one of the few operators in the ECMAScript operator that is related to binary calculations. Let's look at an example:
var num1 = 25; Binary 00000000000000000000000000011001
var num2 = ~num1; Binary 11111111111111111111111111100110
alert (num2); -26

Here, the bitwise non-operation is performed on 25, resulting in a-26. This also verifies the nature of bitwise non-operation: The negative value of the operand minus 1.
Therefore, the following code can also get the same result:
var num1 = 25;
var num2 =-num1-1;
alert (num2); "-26"

Although the above code can return the same result, it is faster because the bitwise is not the lowest performing operation in the numeric representation.

2. Bitwise AND (and)

The bitwise AND operator is represented by a and number character (&), which has two operands. In essence, bitwise and operations align each bit of the two numeric values, and then perform and operations on the two numbers in the same location according to the rules in the following table:

In short, the bitwise AND operation only returns 1 if the corresponding bit of two values is 1 o'clock, and any one is 0, and the result is 0.

Here is an example of performing a bitwise AND operation on 25 and 3:
var result = & 3;
alert (result); 1

3. Bitwise OR (OR)
A bitwise OR operator is represented by a vertical bar symbol (|), which also has two operands. Bitwise OR operation follows the truth table below.

Thus, a bitwise OR operation returns 1 if one bit is 1, and 0 is returned only if two bits are 0.
If you perform a bitwise OR operation on 25 and 3 in the previous bitwise and example, the code looks like this:
var result = 25 | 3;
alert (result); 27

25 with 3 bitwise OR the result is 27:
25 = 0000 0000 0000 0000 0000 0000 0001 1001
3 = 0000 0000 0000 0000 0000 0000 0000 0011
--------------------------------------------
OR = 0000 0000 0000 0000 0000 0000 0001 1011
Both of these values contain 4 1, so you can put each 1 directly into the result. The binary code 11011 equals the decimal value 27.

4. Bitwise XOR OR (XOR)
The bitwise XOR operator is represented by a caret (^) and has two operands. The following is a bitwise XOR truth table.

Bitwise XOR differs from bitwise OR, in that the operation returns 1 if the corresponding two bits are 1 or 0, except that it is only one 1 o'clock on the corresponding bit of two values.
The code for bitwise XOR OR operation on 25 and 3 is as follows:
var result = 25 ^ 3;
alert (result); 26

The result of 25 and 3 bitwise XOR is 26, and its underlying operation is as follows:
25 = 0000 0000 0000 0000 0000 0000 0001 1001
3 = 0000 0000 0000 0000 0000 0000 0000 0011
---------------------------------------------
XOR = 0000 0000 0000 0000 0000 0000 0001 1010
Both values contain 4 1, but the first bit is 1, so the first bit of the result becomes 0. 1 of the other digits do not have a corresponding 1 in another value, and can be placed directly into the result. The binary code 11010 is equal to the decimal value 26 (note that the result is more than a bitwise or small 1).

5. Move left
The left shift operator is represented by the two less than sign (<<), which shifts all bits of the value to the left by the specified number of digits. For example, if you move the value 2 (binary code 10) to the left 5 bits, the result is 64 (binary code is 1000000), the code is as follows:
var oldValue = 2; equals 10 of Binary
var newvalue = OldValue << 5; equals binary 1000000, decimal 64

Note that after shifting to the left, there are 5 extra slots on the right side of the original value. The left shift fills the slots with zeros so that the resulting result is a complete 32-bit binary number (see Figure 3-2).

6. Signed Right Shift
The signed right shift operator is represented by the two greater than sign (>>), which moves the value to the right, but retains the symbol bit (that is, the sign mark). A signed right-shift operation is the opposite of a left-shift operation, meaning that if you move 64 to the right by 5 bits, the result will change back to 2:
var oldValue = 64; equals 1000000 of Binary
var newvalue = OldValue >> 5; equals binary 10, which is the decimal 2

7. Unsigned Right Shift
The unsigned Right shift operator is represented by the 3 greater than sign (>>>), which moves all 32 bits of the value to the right. For positive numbers, the result of an unsigned right shift is the same as a signed right shift. For example, if you move the 64 unsigned right by 5 bits, the result is still 2:
var oldValue = 64; equals 1000000 of Binary
var newvalue = OldValue >>> 5; equals binary 10, which is the decimal 2

Boolean operator

In a programming language, the importance of Boolean operators is comparable to equal operators. If you do not have the ability to test two value relationships, statements such as if...else and loops will be useless. There are 3 Boolean operators: Non (not), with (and), and or (or).

1. Logical Non-

The logical non-operator consists of an exclamation mark (! ) represents any value that can be applied to the ECMAScript. Regardless of the data type of this value, this operator returns a Boolean value. The logical non-operator first converts its operand to a Boolean value and then deserializes it. In other words, the logical non-operator follows the following rules:
? Returns False if the operand is an object;
? Returns true if the operand is an empty string;
? Returns False if the operand is a non-empty string;
? Returns true if the operand is a numeric value of 0;
? Returns False if the operand is any non-0 value (including infinity);
? Returns true if the operand is null;
? Returns true if the operand is Nan;
? Returns true if the operand is undefined.
The following examples show the results of applying the above rules:
alert (!false); True
Alert (! " Blue "); False
alert (!0); True
Alert (! NaN); True
Alert (! ""); True
Aler T (!12345); False

A logical non-operator can also be used to convert a value to its corresponding Boolean value. Using two logical non-operators, in effect, simulates the behavior of a Boolean () transformation function. Where the first logical non-operation returns a Boolean value based on whatever operand, and the second logical non-action deserializes the Boolean value, the Boolean value that the value really corresponds to is obtained. Of course, the end result is the same as using the Boolean () function for this value, as shown in the following example:

Alert (!! " Blue "); True
Alert (!! 0); False
Alert (!! NaN); False
Alert (!! "); False
Alert (!! 12345); True

2. Logic and

The logic and operators are represented by two and numbers (&&), with two operands, as shown in the following example:
var result = True && false;
Logic and the truth table are as follows:

Logic and operations can be applied to operands of any type, not just Boolean values. In the case where an operand is not a Boolean value, the logic and operation do not necessarily return a Boolean value, at which point it follows the following rules:
? Returns the second operand if the first operand is an object;
? If the second operand is an object, the object is returned only if the value of the first operand evaluates to true;
? If the two operands are objects, the second operand is returned;
? Returns null if one of the operands is null;
? If one of the operands is Nan, a nan is returned;
? If one of the operands is undefined, the undefined is returned.
Logic and operations are short-circuiting operations where the second operand is no longer evaluated if the first operand can determine the result.
For logic and operations, if the first operand is false, the result is no longer likely to be true regardless of the value of the second operand. Take a look at the following example:
var found = true;
var result = (found && someundefinedvariable); An error will occur here
alert (result); This line does not execute

In the above code, an error occurs when executing the logic and operation because the variable someundefinedvariable is not declared. Because the value of the variable found is true, the logic and operator continue to evaluate the variable someundefinedvariable.
However, someundefinedvariable is not defined and therefore causes an error. This means that undefined values cannot be used in logic and operations. If, as in the example below, the value of found is set to False, no error occurs:
var found = false;
var result = (found && someundefinedvariable); No error occurs
alert (result); Will execute ("false")

In this example, the warning box is displayed. No matter whether the variable someundefinedvariable is defined or not, it is never evaluated, because the value of the first operand is false. This means that the result of the logic and operation must be false, and there is no need to evaluate the operand to the right of &&. Always keep in mind that it is a short-circuit operator when using logic and operators.

3. Logical OR

A logical OR operator consists of two vertical bar symbols (| | ) indicates that there are two operands, as shown in the following example:
var result = True | | False
The logical or Truth table is as follows:

Similar to logic and operations, if there is an operand that is not a Boolean value, logic or does not necessarily return a Boolean value; At this point, it follows the following rules:
? If the first operand is an object, the first operand is returned;
? Returns the second operand if the evaluation result of the first operand is false;
? If the two operands are objects, the first operand is returned;
? Returns NULL if all two operands are null;
? If the two operands are Nan, a nan is returned;
? If the two operands are undefined, the undefined is returned.
Like logic and operators, a logic or operator is also a short-circuit operator. In other words, if the first operand evaluates to true, the second operand is not evaluated. Let's look at an example:
var found = true;
var result = (Found | | someundefinedvariable); No error occurs
alert (result); Will execute ("true")

This example, like the previous example, has no definition of the variable someundefinedvariable. However, because the value of the variable found is true, and the variable someundefinedvariable is never evaluated, the result outputs "true". If you change the value of found to false, as in the example below, it will result in an error:
var found = false;
var result = (Found | | someundefinedvariable); An error will occur here
alert (result); This line does not execute

We can use the logic or this behavior to avoid assigning null or undefined values to variables. For example:
var myObject = Preferredobject | | Backupobject;
In this example, the variable MyObject will be given one of the two values after the equals sign. The variable preferredobject contains the value assigned to the variable MyObject, and the variable backupobject is responsible for providing the fallback value if the Preferredobject does not contain a valid value. If the value of Preferredobject is not NULL, then its value is assigned to MyObject, and if NULL, the value of Backupobject is assigned to MyObject. This pattern is often used in the assignment statements of ECMAScript programs, which are also used in this book.

Multiply sex operator

ECMAScript defines 3 multiplicative operators: multiplication, division, and modulo. These operators are similar to the corresponding operators in Java, C, or Perl, except that automatic type conversions are performed if the operands are non-numeric. If an operand that participates in multiplicative calculations is not a numeric value, the background will first use the number () transformation function to convert it to a numeric value. That is, an empty string will be treated as 0, and a Boolean value of true will be treated as 1.


1. Multiplication
The multiplication operator is represented by an asterisk (*) to calculate the product of two numbers. Its syntax is similar to C, as shown in the following example:
var result = 34 * 56;
In cases where special values are handled, the multiplication operator follows the following special rules:
? If the operands are numeric, perform a regular multiplication calculation, that is, the result of multiplying two positive or two negative numbers is positive, and if only one operand is signed, the result is a negative number. If the product exceeds the representation range of the ECMAScript value, the Infinity or-infinity is returned;
? If one of the operands is Nan, the result is Nan;
? If the infinity is multiplied by 0, the result is Nan;
? If the Infinity is multiplied by a value other than 0, the result is Infinity or-infinity, depending on the symbol of the signed operand;
? If the infinity is multiplied with infinity, the result is infinity;
? If there is an operand that is not a numeric value, call number () in the background to convert it to a numeric value, and then apply the rule above.

2. Division
The division operator is represented by a slash sign (/) that performs the calculation of the second operand in addition to the first operand, as shown in the following example:
var result = 66/11;
Like the multiplication operator, the division operator has special processing rules for special values. These rules are as follows:
? If the operands are numeric, perform a regular division calculation, that is, the result of dividing two positive or two negative numbers is a positive number, and if only one operand is signed, the result is negative. If the quotient exceeds the representation range of the ECMAScript value, the Infinity or-infinity is returned;
? If one of the operands is Nan, the result is Nan;
? If the infinity is infinity, the result is Nan;
? If 0 is removed by 0, then the result is Nan;
? If a non-zero finite number is removed by 0, the result is Infinity or-infinity, depending on the symbol of the signed operand;
? If Infinity is removed by any non-0 value, the result is Infinity or-infinity, depending on the symbol of the signed operand;

? If there is an operand that is not a numeric value, call number () in the background to convert it to a numeric value, and then apply the rule above.


3. Mould-Finding
The modulo (remainder) operator is represented by a percent semicolon (%) and is used as follows:
var result = 26% 5; equals 1
Similar to the other two multiplicative operators, the modulo operator follows special rules to handle special values:
? If the operands are numeric, perform a general division calculation and return the remainder;
? If the divisor is an infinity value and the divisor is a finite number, the result is Nan;
? If the divisor is a finite large number and the divisor is zero, the result is Nan;
? If the infinity is infinity, the result is Nan;
? If the divisor is a finite number and the divisor is an infinite number, the result is a divisor;
? If the divisor is zero, the result is 0;
? If there is an operand that is not a numeric value, call number () in the background to convert it to a numeric value, and then apply the rule above.

Additive operator

1. Addition
The usage of the addition operator (+) is as follows:
var result = 1 + 2;
If the two operators are numeric, perform a regular addition calculation, and then return the results according to the following rules:
? If one of the operands is Nan, the result is Nan;
? If it is infinity plus infinity, then the result is infinity;
? If it is-infinity plus-infinity, then the result is-infinity;
? If it is Infinity plus-infinity, the result is Nan;
? If it is +0 plus +0, the result is +0;
? If it is 0 plus 0, then the result is 0;
? If it is +0 plus 0, the result is +0.
However, if you have an operand that is a string, you should apply the following rule:
? If the two operands are strings, the second operand is stitched together with the first operand;
? If only one operand is a string, the other operand is converted to a string, and then the two strings are stitched together.
If an operand is an object, numeric, or Boolean value, call their ToString () method to obtain the corresponding string value, and then apply the preceding rule about the string. For undefined and null, the string () function is called separately and the strings "undefined" and "null" are obtained.
Here are a few examples:
var result1 = 5 + 5; Two number of values added
alert (RESULT1); 10

var result2 = 5 + "5"; Add a number and a string
Aler T (RESULT2); "55"

The above code illustrates the difference between the addition operator and the two modes. The first line of code demonstrates the normal situation, where 5+5 equals 10 (numeric). However, if you change an operand to the string "5", the result becomes "55" (the string value) because the first operand is also converted to "5".
Ignoring the data types in the addition operation is one of the most common errors in ECMAScript programming. Let's look at one more example:
var num1 = 5;
var num2 = 10;
var message = "The sum of 5 and Ten is" + NUM1 + num2;
alert (message); "The sum of 5 and is 510"

In this example, the value of the variable message is the result of performing two addition operations. One might assume that the last string was "the sum of 5 and is 15", but the actual result was "the sum of 5 and is 510".
This happens because each addition operation is performed independently. The first addition operation spliced a string with a numeric value (5), and the result is a string. The second addition uses this string to add another value (10), and of course it gets a string. If you want to perform an arithmetic calculation on a numeric value before stitching the result with a string, you should use parentheses as follows:
var num1 = 5;
var num2 = 10;
var message = "The sum of 5 and Ten is" + (num1 + num2);
alert (message); "The sum of 5 and is 15"

In this example, a pair of parentheses encloses two numeric variables, which tells the parser to calculate the result before stitching the result together with the string. Thus, the result "the sum of 5 and is 15" was obtained.

2. Subtraction
The subtraction operator (-) is another extremely common operator, and its usage is as follows:
var result = 2-1;
Like the addition operator, the subtraction operator in ECMAScript also needs to follow some special rules when dealing with various data type conversions, as follows:
? If all two operators are numeric, perform a regular arithmetic subtraction operation and return the result;
? If one of the operands is Nan, the result is Nan;
? If it is infinity minus infinity, the result is Nan;
? If it is-infinity minus-infinity, the result is Nan;
? If it is Infinity minus-infinity, the result is Infinity;
? If it is-infinity minus Infinity, the result is-infinity;
? If +0 minus +0, the result is +0;
? If it is +0 minus-0, the result is-0;

? If it is-0 minus-0, the result is +0;
? If an operand is a string, Boolean, NULL, or undefined, the number () function is called first in the background to convert it to a numeric value, and then the subtraction calculation is performed based on the preceding rule. If the result of the conversion is Nan, the result of the subtraction is Nan;
? If an operand is an object, the valueof () method of the object is called to get the numeric value that represents the object. If the resulting value is Nan, the result of the subtraction is Nan. If the object does not have a valueof () method, its ToString () method is called and the resulting string is converted to a numeric value.
The following examples show the above rules:
var result1 = 5-true; 4, because true is converted to 1
var result2 = NaN-1; NaN
var result3 = 5-3; 2
var result4 = 5-""; 5, because "" was converted into 0
var result5 = 5-"2"; 3, because "2" was converted to 2.
var result6 = 5-null; 5, because NULL is converted to 0

JavaScript Advanced Program Design reading notes---operation selector

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.