I am small and live in Wuhan, do two years of new media, ready to use 6 months time to switch to the front end of the industry.

Lesson Objective for today

Yesterday, based on some page search, I learned many methods and attributes of String data type in ES basic concepts in chapter 3 of JavaScirpt Advanced Programming (3rd edition), and found that there are still many basic knowledge points to supplement learning. So, today is a good day to study the 3.5 operator in chapter 3 based on search. Come on, small and !!!!


Unary operator

Increment operator

Basic instructions

The increment operator increments its operand by one and returns a numeric value.

  • If you use postfix, where the operator comes after the operand (such as x++), the value is returned before incrementing.
  • If you use prefix, where the operator precedes the operand (such as ++x), the value will be returned after incrementing.

grammar

Operators: x++ or ++xCopy the code

The sample

/ / rear
var x = 3;
y = x++; 
// y = 3, x = 4

/ / pre -
var a = 2;
b = ++a; 
// a = 3, b = 3
Copy the code

Matters needing attention

Increment operators apply not only to numeric values, but also to strings, booleans, floating-point values, and objects. Increment operators follow the following rules when applied to different values.

  • When applied to a string containing a valid numeric character, it is converted to a numeric value, the string variable to a numeric variable, and then incremented.
  • When applied to a string that contains no valid numeric characters, the value of the variable is set to NaN, turning the string variable into a numeric variable.
  • When applied to a Boolean value false, it is converted to 0, a Boolean variable to a numeric variable, and then incremented by one.
  • When applied to a Boolean value true, it is converted to 1, a Boolean variable to a numeric variable, and then incremented by one.
  • When applied to a floating point value, the incrementing operation is performed.
  • When applied to an object, the valueOf() method of the object is first called to get a value that can be manipulated. The previous rules are then applied to that value, and if the converted value is NaN, the toString() method is called, and the same rules are applied to turn the object variable into a numeric variable.
var s1 = "2";
var s2 = "z";
var b1 = false;
var b2 = true;
var f = 1.1;
var o = {
 valueOf: function(){
  return - 1; }};
s1++;//  3
s2++;// NaN
b1++;/ / 1
b2++;/ / 2
f++;/ / 2.1
o++;/ / 0
Copy the code

Decrement operator

Basic instructions

The decrement operator subtracts its operand by 1 and returns a numeric value.

  • If used postpended (such as x–), the value is returned before decrement.
  • If it is used before (such as –x), the value is returned after decrement.

grammar

Operator: x-- or --xCopy the code

The sample

/ / rear
var x = 3;
y = x--; // y = 3, x = 2

/ / pre -
var a = 2;
b = --a; // a = 1, b = 1
Copy the code

Matters needing attention

The decrement operator applies not only to numeric values, but also to strings, booleans, floating-point values, and objects. The same rules apply to different values as the increment operator.

var s1 = "2";
var s2 = "z";
var b1 = false;
var b2 = true;
var f = 1.1;
var o = {
 valueOf: function(){
  return - 1; }};
s1--;//  1
s2--;// NaN
b1--;/ / - 2
b2--;// -1
f--;/ / 0.10000000000000009
o--;/ / - 2
Copy the code

Unary addition and subtraction operators

Basic instructions

Unary addition and subtraction are familiar to most developers, and the two ECMAScript operators work exactly as they do in math books. Basically, the + or – operators are added before the numeric value.

  • The plus sign (+) is placed before the value and has no effect on the value.
  • The minus sign (-) precedes the number to indicate that it is a negative number.

Used primarily for basic arithmetic operations, but also for data type conversions.


grammar

Operator: x-- or --xCopy the code

The sample

var s1 = "2";
var s2 = "z";
var b1 = false;
var b2 = true;
var f = 1.1;
var o = {
 valueOf: function(){
  return - 1; }};
s1 = +s1;//  2
s2 = -s2;// NaN
b1 = +b1;/ / 0
b2 = -b2;// -1
f = +f;/ / 1.1
o = -o;/ / 1
Copy the code

Matters needing attention

The unary plus operator, which precedes its operand, evaluates the value of its operand and attempts to convert it to a value if it is not a value.

Although unary minus can also convert non-numeric types, unary plus is the fastest way to convert other objects to numeric values and is the most recommended because it does not perform any unnecessary operations on numeric values. It can convert strings to integer and floating point forms, as well as non-string values true, false, and NULL.

Decimal and hexadecimal format strings can also be converted to numeric values. Negative strings can also be converted to numeric values (not for hexadecimal). If it cannot resolve a value, it evaluates to NaN.


An operator

Basic instructions

Bitwise operators treat their operands as 32-bit sequences of bits (zeros and ones) rather than decimal, hexadecimal, or octal values.

For example, the decimal number 9 is 1001 in binary notation. Bitwise operators operate on the binary form of numbers, but the return value is still a standard JavaScript value.

The operator usage describe
Bitwise AND (AND) a & b For each bit, the result is 1 only if the corresponding bit bits of both operands are 1; otherwise, it is 0.
Bitwise OR (OR) a | b For each bit, the result is 1 if there is at least one 1 in the corresponding bit of the two operands, and 0 otherwise.
Bitwise XOR a ^ b For each bit, the result is 1 if there is one and only one 1 in the corresponding bit of the two operands, and 0 otherwise.
Bitwise NOT ~ a Invert the operand’s bits, i.e., 0 becomes 1,1 becomes 0.
Left shift (L) a << b willaThe binary form of is shifted to the leftb(< 32) bits, filled with zeros on the right.
There’s a sign shift to the right a >> b Shift the binary representation of A to the rightb(< 32) bits, discarding the removed bits.
Unsigned shift to the right a >>> b Shift the binary representation of A to the rightb(< 32) bits, discarding the removed bits and padding the left side with 0.

Signed 32-bit integer

The operands of all bitwise operators are converted to signed 32-bit integers of the form two’s complement. The complement form is the counterpart of a number whose negative counterpart (such as 5 and -5) is the sum of all the bits in the value, which is then added by 1. To reverse a bit is to perform a non-bit operation on the value, which is the inverse of the value.

The complement guarantees that when a number is positive, its leftmost bit is 0 and when a number is negative, its leftmost bit is 1. Therefore, the leftmost bit is called the sign bit (sign bit).

0 is the integer consisting of all bits of the number 0.

0 (base 10) = 00000000000000000000000000000000 (base 2)
Copy the code

-1 is an integer consisting of all bits of the number 1.

- 1 (base 10) = 11111111111111111111111111111111 (base 2)
Copy the code

Conceptually, bitwise logical operators follow the following rules

  • The operands are converted to 32-bit integers represented by a sequence of bits (0 and 1). Numbers larger than 32 bits are discarded. For example, the following integers with more than 32 bits are converted to 32 bits
Before conversion:11100110111110100000000000000110000000000001After the transformation:10100000000000000110000000000001
Copy the code
  • Each bit of the first operand matches the corresponding bit of the second operand: first to first, second to second, and so on.
  • The bitwise operator is applied to each pair of bits, resulting in the new bit value.

Bitwise NOT (NOT)

Performs a NOT operation on each bit. The result is the reverse of a.

A truth table that is not an operation

a NOT a
0 1
1 0
9 (base 10) = 00000000000000000000000000001001 (base 2) -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -9 (base 10) = 11111111111111111111111111110110 (base 2) = - 10 (base 10)
Copy the code

The bitwise nonoperation on any number x results in -(x + 1). For example, ~5 results in -6.

Use examples with indexOf

var str = 'rawr';
var searchFor = 'a';
// This is another way to determine the condition if (-1* str.indexof ('a') <= 0)
if (~str.indexOf(searchFor)) {
  // searchFor is contained in the string
} else {
  // searchFor is not included in the string
}
// return value of (~ str.indexof (searchFor))
// r == -1
// a == -2
// w == -3
Copy the code

The bitwise AND (AND)

An AND operation is performed on each pair of bits. A AND b are only 1 if both a AND B are 1. The truth table for the operation is as follows

a b a AND b
0 0 0
0 1 0
1 0 0
1 1 1
9 (base 10) = 00000000000000000000000000001001 (base 2)
    14 (base 10) = 00000000000000000000000000001110 (base 2) -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --14 & 9 (base 10) = 00000000000000000000000000001000 (base 2) = 8 (base 10)
Copy the code

Bitwise and operations on either value x and 0 result in 0. The bitwise and operation on either value x and -1 results in x.


The bitwise OR (OR)

Performs an OR operation on each pair of bits. If a OR B is 1, then a OR B is 1.

Or the truth table of the operation:

a b a OR b
0 0 0
0 1 1
1 0 1
1 1 1
9 (base 10) = 00000000000000000000000000001001 (base 2)
    14 (base 10) = 00000000000000000000000000001110 (base 2) -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --14 | 9 (base 10) = 00000000000000000000000000001111 (base 2) = 15 (base 10)
Copy the code

The bitwise or operation of any number x with 0 yields x. The bitwise or operation of any number x with -1 yields -1. A few more examples

1 | 0 ;                       / / 1
1.1 | 0 ;                     / / 1
'asfdasfda' | 0 ;             / / 0
0 | 0 ;                       / / 0
(- 1) | 0 ;                    // -1
(1.5646) | 0 ;               // -1
[] | 0 ;                      / / 0
({}) | 0 ;                    / / 0
"123456" | 0 ;            / / 123456
1.23 e2 | 0;               / / 123
1.23 e12 at 11:45 | 0;              / / 1639353344
1.23 e2 | 0;              / / - 123
1.23 e12 at 11:45 | 0;             / / - 1639353344
Copy the code

Bitwise XOR

An XOR operation is performed on each pair of bits. When a and B are different, a XOR b is equal to 1. Xor operation truth table:

a b a XOR b
0 0 0
0 1 1
1 0 1
1 1 0
9 (base 10) = 00000000000000000000000000001001 (base 2)
    14 (base 10) = 00000000000000000000000000001110 (base 2) -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --14 ^ 9 (base 10) = 00000000000000000000000000000111 (base 2) = 7 (base 10)
Copy the code

The xor operation of any number x with 0 results in x. Xor of any value x with -1 yields ~x.


Shift to the left

This operator moves the first operand to the left by the specified number of digits. Bits removed to the left are discarded and zeros are added to the right. For example, 9 << 2 yields 36

9 (base 10) :00000000000000000000000000001001 (base 2) -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --9 << 2 (base 10) :00000000000000000000000000100100 (base 2) = 36 (base 10)
Copy the code

You move y bits to the left of the number x to get x times 2.


Signed shift to the right

This operator moves the first operand to the right by the specified number of digits. Bits moved to the right are discarded and the leftmost bits are copied to fill the left side. Since the new leftmost bit is always the same as before, the sign bit is not changed. That’s why it’s called “symbol propagation.” For example, 9 >> 2 gets 2

9 (base 10) :00000000000000000000000000001001 (base 2) -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --9 >> 2 (base 10) :00000000000000000000000000000010 (base 2) = 2 (base 10)
Copy the code

In contrast, -9 >> 2 gives -3 because the sign is preserved.

     9 - (base 10) :11111111111111111111111111110111 (base 2) -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --9 - >> 2 (base 10) :11111111111111111111111111111101 (base 2) = - 3 (base 10)
Copy the code

Unsigned shift to the right

This operator moves the first operand to the right by the specified number of digits. Bits moved to the right are discarded and the left side is filled with zeros. Because the sign bit becomes zero, the result is always non-negative. (Even if you move 0 bits to the right, the result is non-negative.) For non-negative numbers, signed and unsigned right shifts always return the same result. For example 9 >>> 2 and 9 >> 2 return 2

9 (base 10) :00000000000000000000000000001001 (base 2) -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --9 >>> 2 (base 10) :00000000000000000000000000000010 (base 2) = 2 (base 10)
Copy the code

But it’s not the same for negative numbers. -9 >>> 2 generates 1073741821. This is different from -9 >> 2

9 - (base 10) :11111111111111111111111111110111 (base 2) -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --9 - >>> 2 (base 10) :00111111111111111111111111111101 (base 2) = 1073741821 (base 10)
Copy the code

Integrated case

Example: flag bits and masks

Bitwise operations are often used to create, process, and read sequences of flag bits, a binary-like variable. It is possible to use variables instead of sequences of flag bits, but this saves memory (1/32). For example, there are four flag bits

  • Flag bit A: We have Ant
  • Flag bit B: We have bat
  • Flag bit C: We have cat
  • Flag bit D: We have duck

Flag bits are represented by the bit sequence DCBA.

  • When a bit is set, it has the value 1.
  • When cleared, it has a value of 0.

For example, the binary value of flags is 0101

var flags = 5;   // Binary 0101
Copy the code

This value represents:

  • Flag bit A is true (we have ant);
  • Flag bit B is false (we don’t have bat);
  • Flag bit C is true (we have cat);
  • Flag bit D is false (we don’t have duck);

Because the bit operations is 32-bit, 0101 is actually 00000000000000000000000000000101. Because the extra zeros in front don’t make any sense, they can be ignored.


** BITmask ** is a sequence of bits that read flag bits by and/or. A typical primitive mask that defines each flag bit is as follows

var FLAG_A = 1; / / 0001
var FLAG_B = 2; / / 0010
var FLAG_C = 4; / / 0100
var FLAG_D = 8; / / 1000
Copy the code

New masks can be created using logical operations on the above masks. For example, the mask 1011 can be obtained by FLAG_A, FLAG_B, and FLAG_D logic:

var mask = FLAG_A | FLAG_B | FLAG_D; / / 0001 | 0010 | 1000 = > 1011
Copy the code

A particular bit can be obtained by performing a logical and operation with the mask, and a specific bit can be obtained by removing irrelevant bits with the operation with the mask. For example, the mask 0100 can be used to check if flag bit C is set

// If we have cat
if (flags & FLAG_C) { // 0101 & 0100 => 0100 => true
   // do stuff
}
Copy the code

A mask table with more than one bit set has any/or meaning. For example, the following two expressions are equivalent

// If we have at least one bat or cat
// (0101 & 0010) || (0101 & 0100) => 0000 || 0100 => true
if ((flags & FLAG_B) || (flags & FLAG_C)) {
   // do stuff
}
Copy the code
// If we have at least one bat or cat
var mask = FLAG_B | FLAG_C; / / | = > 0110 0100 0010
if (flags & mask) { // 0101 & 0110 => 0100 => true
   // do stuff
}
Copy the code

The flag bit can be set by performing or operation with the mask. The bit 1 in the mask can be set to the corresponding bit. For example, mask 1100 can be used to set bits C and D

// We have cat and duck
var mask = FLAG_C | FLAG_D; / / | = > 1100 1000 0100
flags |= mask;   / / | = > 1101 1100 0101
Copy the code

The flag bit can be cleared by the and operation of the mask. The bit 0 in the mask can be set to the corresponding bit. The mask can be obtained by performing non-operations on the primitive mask. For example, mask 1010 can be used to clear flag bits A and C

// We don't have ant or cat
var mask = ~(FLAG_A | FLAG_C); / / ~ 0101 = > 1010
flags &= mask;   // 1101&1010 => 1000
Copy the code

The above mask can also be obtained by ~FLAG_A & ~FLAG_C (De Morgan’s Law)

// We don't have ant or cat
var mask = ~FLAG_A & ~FLAG_C;
flags &= mask;   // 1101&1010 => 1000
Copy the code

Flag bits can be switched using xOR operations. All bits with a value of 1 can be switched to the corresponding bit. For example, mask 0110 can be used to switch flag bits B and C:

/ / if we haven't bat before, so we now have the bat / / but if we already have one, so we don't have any now / / the cat is the same situation var mask = FLAG_B | FLAG_C; flags = flags ^ mask; // 1100 ^ 0110 => 1010Copy the code

Finally, all flag bits can be flipped by non-operation

// entering parallel universe...
flags = ~flags;    / / ~ 1010 = > 0101
Copy the code

Segments of conversion

A binary number [String] (https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/String) is converted to a decimal [Number](https://developer.mozilla.org/zh-CN/docs/JavaScript/Reference/Global_Objects/Number):

var sBinString = "1011";
var nMyNumber = parseInt(sBinString, 2);
alert(nMyNumber); / / print 11
Copy the code

Converts a decimal Number to a binary String

var nMyNumber = 11;
var sBinString = nMyNumber.toString(2);
alert(sBinString); / / print 1011
Copy the code

Automatic mask creation

If you need to create a mask from a list of Boolean values, you can

function createMask () {
  var nMask = 0, nFlag = 0, nLen = arguments.length > 32 ? 32 : arguments.length;
  for (nFlag; nFlag < nLen; nMask |= arguments[nFlag] << nFlag++);
  return nMask;
}
var mask1 = createMask(true.true.false.true); // 11, i.e.: 1011
var mask2 = createMask(false.false.true); // 4, i.e.: 0100
var mask3 = createMask(true); // 1, i.e.: 0001
// etc.
alert(mask1); / / print 11
Copy the code

Inverse algorithm: Get Boolean array from mask

If you want to get Boolean Array from the mask

function arrayFromMask (nMask) {
  // nMask must be between -2147483648 and 2147483647
  if (nMask > 0x7fffffff || nMask < -0x80000000) { 
    throw new TypeError("arrayFromMask - out of range"); 
  }
  for (var nShifted = nMask, aFromMask = []; nShifted; 
       aFromMask.push(Boolean(nShifted & 1)), nShifted >>>= 1);
  return aFromMask;
}
var array1 = arrayFromMask(11);
var array2 = arrayFromMask(4);
var array3 = arrayFromMask(1);
alert("[" + array1.join(",") + "]");
/ / print "true, true, false, true]", i.e. for: 11, i.e. for: 1011
Copy the code

You can test both algorithms simultaneously…

var nTest = 19; // our custom mask
var nResult = createMask.apply(this, arrayFromMask(nTest));
alert(nResult); / / 19
Copy the code

Just for educational purposes (because of the number.toString (2) method), we show how to modify the arrayFromMask algorithm to return binary strings via Number instead of Boolean Array

function createBinaryString (nMask) {
  // nMask must be between -2147483648 and 2147483647
  for (var nFlag = 0, nShifted = nMask, sMask = ""; nFlag < 32;
       nFlag++, sMask += String(nShifted >>> 31), nShifted <<= 1);
  return sMask;
}
var string1 = createBinaryString(11);/ / 00000000000000000000000000001011
var string2 = createBinaryString(4);/ / 00000000000000000000000000000100
var string3 = createBinaryString(1);/ / 00000000000000000000000000000001

Copy the code

Boolean operator

Based on description

Logical operators are usually used for Boolean (logical) values. In this case, they return a Boolean value. However, && and | | operator returns a value of the specified operand, as a result, these operators are also used in a Boolean value. They also return a non-Boolean value.

The logical operators are shown in the following table (where _exPR_ may be any type, not necessarily a Boolean value):

The operator grammar instructions
Logic AND, AND (&&) _expr1_ && _expr2_ ifexpr**1**Can be converted totrue, the returnexpr**2**; Otherwise, returnexpr**1**.
Logic OR, OR (||) _expr1_ || _expr2_ ifexpr**1**Can be converted totrue, the returnexpr**1**; Otherwise, returnexpr**2**.
Logical NOT, NOT (!) ! _expr_ ifexprCan be converted totrue, the returnfalse; Otherwise, returntrue.

If a value can be converted to true, it is called truthy, and if it can be converted to false, it is called falsy. Expressions that will be converted to false are:

  • null;
  • NaN;
  • 0;
  • Empty string ("" or ' 'The or ` ` ` `);
  • undefined.

Although && and | | operators can use a Boolean value of the operand, but they can still be seen as Boolean operators, because they always return value can be converted to Boolean value. If you want to explicitly convert their return value (or expression) to a Boolean, use a double non-operator (that is!!). Or Boolean constructors.


Logic is not

The following code is! Example of the (logical non) operator

n1 = ! true // ! T returns false n2 =! false // ! F returns true n3 =! "' / /! F returns true n4 =! 'Cat' // ! T returns falseCopy the code

Double a (!!!!!) operator

One scenario where a double non-operator might be used is to explicitly cast an arbitrary value to its corresponding Boolean value. This conversion is based on the “truthyness” and “falsyness” of the converted value. The same conversion can be done using Boolean functions.

n1 = !!true                   / /!!!!! Truthy returns truen2 = !! {}/ /!!!!! Truthy returns true: any object is Truthy's...n3 = !! (new Boolean(false))   / /... Even Boolean objects that.valueof () returns false!
n4 = !!false                  / /!!!!! Falsy returns false
n5 = !!""                     / /!!!!! Falsy returns false
n6 = !!Boolean(false)         / /!!!!! Falsy returns false
Copy the code

Logic and

The following code is an example of the && (logical and) operator

a1 = true  && true      // t && t returns true
a2 = true  && false     // t && f returns false
a3 = false && true      // f && t returns false
a4 = false && (3= =4)  // f && f returns false
a5 = "Cat" && "Dog"     // t &&t returns "Dog"
a6 = false && "Cat"     // f && t returns false
a7 = "Cat" && false     // t && f returns false
a8 = ' '    && false     // f &&f returns ""
a9 = false && ' '        // f && f returns false
Copy the code

Logic or

The following code is | | (logical or operator of the sample.

o1 = true  || true      / / t | | t return true
o2 = false || true      / / f | | t return true
o3 = true  || false     / / t | | f returns true
o4 = false| | -3= =4)  / / f | | f returns false
o5 = "Cat" || "Dog"     / / t | | t return to the "Cat"
o6 = false || "Cat"     / / f | | t return to the "Cat"
o7 = "Cat" || false     / / t | | f to return to the "Cat"
o8 = ' '    || false     / / f | | f returns false
o9 = false || ' '        / / f | | f return ""
Copy the code

Short circuit calculation

Since logical expressions are evaluated from left to right, the following rules can also be used for short-circuiting:

  • (some falsy expression) && (_expr)_The result of short circuit calculation is false.
  • (some truthy expression) || _(expr)_The result of short-circuit calculation is true.

Short-circuited means that the EXPR part of the expression above is not executed, so any side effects of EXPR will not take effect (for example, if expr was a function call, the call would not occur). The reason for this is that the value of the entire expression is already determined after the first operand is evaluated. Look at an example:

function A(){ console.log('called A'); return false; }
function B(){ console.log('called B'); return true; }
console.log( A() && B() );
// logs "called A" due to the function call,
// then logs false (which is the resulting value of the operator)
console.log( B() || A() );
// logs "called B" due to the function call,
// then logs true (which is the resulting value of the operator)
Copy the code

Operator priority

Note that the following expression results differently because of operator precedence. The operation enclosed in parentheses on the right becomes a separate expression.

false &&  true || true      // Result is true
false && (true || true)     // The result is false
Copy the code

Integrated case

There are correlation conversions between logical operators ~~~~

The transformation direction Transformation before After the transformation
Convert AND to OR bCondition1 && bCondition2 ! (! bCondition1
Convert OR to AND bCondition1 || bCondition2 ! (! bCondition1 && ! bCondition2)
Delete nested AND bCondition1 || (bCondition2 && bCondition3) bCondition1
Delete the nested OR bCondition1 && (bCondition2

Multiplicative operator

The multiplication

Basic instructions

The result of the multiplication operator is a product of operands.


grammar

Operator: x * yCopy the code

The sample

2 * 2 / / 4
2 - * 2 / / - 4
Infinity * 0 // NaN
Infinity * Infinity // Infinity
"foo" * 2 // NaN
Copy the code

division

Basic instructions

The result of a division operator is the quotient of the operand, where the left operand is the dividend and the right operand is the divisor.


grammar

Operator: x/yCopy the code

The sample

1 / 2      // Returns 0.5 in JavaScript
1 / 2      // Returns 0 in Java
// (the number does not need to be an unambiguous float)

1.0 / 2.0  // Returns 0.5 in either JavaScript or Java

2.0 / 0    // Return Infinity in JavaScript
2.0 / 0.0  // return Infinity
2.0 / 0.0 // Return -infinity in JavaScript
Copy the code

modulus

Basic instructions

The remainder operator returns the modulo of the first operand over the second operand, that is, var1 over var2, where var1 and var2 are variables. The modulo function is the remainder of var1 divided by var2.


grammar

Operator: var1 % var2Copy the code

The sample

12 % 5 / / 2
- 1 % 2 // -1
NaN % 2 // NaN
1 % 2 / / 1
2 % 3 / / 2
4 - % 2 / / - 0
5.5 % 2 / / 1.5
Copy the code

power

Basic instructions

The power operator returns the first operand as the base and the second as the power of the exponent. That is, var1 ‘ ‘var2, where var1 and var2 are its operands. Exponentiation operators are right associative. A ** b ** C is the same as a ** (b ** c).


grammar

Operator: var1 ** var2Copy the code

The sample

2 ** 3 / / 8
3 ** 2 / / 9
3 ** 2.5 / / 15.588457268119896
10 ** - 1 / / 0.1
NaN ** 2 // NaN

2 ** 3 ** 2 / / 512
2* * (3 ** 2) / / 512
(2 ** 3) * *2 / / 64

// If you want to reverse the sign of the result of an exponentiation, you can do this- (2 ** 2) / / - 4

// Force exponentiation expressions to have a negative cardinality
(2 -) * *2 / / 4
Copy the code

Matters needing attention

Most languages, including PHP or Python, include exponents (typically the symbol ^ or **). Power operators in these languages have higher precedence than other unary operators, such as one + or one -.

But as an exception, in Bash, the ** operator is designed to have lower precedence than the unary operator. In the latest version of JavaScript (ES2016), the use of ambiguous exponentiation expressions is prohibited.

For example, the base cannot be followed by the unary operator (+/-/~/! / delete/void/typeof).

2 - ** 2; 
// Illegal expression. Wrap left hand side or entire exponentiation in parentheses.
// Is equal to 4 in Bash, but is generally equal to -4 in other languages
// Is incorrect in JavaScript because it can be ambiguous
- (2 ** 2);
// the author's intent is obvious in JavaScript
Copy the code

The additive operator

add

Basic instructions

The addition operator is used to sum values or concatenate strings.


grammar

Operator: x + yCopy the code

The sample

// Number + Number -> add the Number
1 + 2 / / 3

// Boolean + Number -> Add numbers
true + 1 / / 2

// Boolean + Boolean -> Add numbers
false + false / / 0

// Number + String -> String connection
5 + "foo" // "5foo"

// String + Boolean -> String join
"foo" + false // "foofalse"
 // String + String -> String connection "foo" + "bar" // "foobar" Copy the code

subtraction

Basic instructions

The subtraction operator subtracts two operands, resulting in their difference.


grammar

Operator: x-yCopy the code

The sample

5 - 3 / / 2
3 - 5 / / - 2
"foo" - 3 // NaN
Copy the code

Relational operator

Greater than operator (>)

The greater than operator returns true only if the left-hand operand is greater than the right-hand operand

grammar

x > y

example

4 > 3 // true
Copy the code

Greater than or equal to operator (>=)

The greater than or equal operator returns true if the left-hand operand is greater than or equal to the right-hand operand

grammar

x >= y

example

4> =3 // true
3> =3 // true
Copy the code

Less than operator (<)

The less-than operator returns true only if the left-hand operand is less than the right-hand operand

grammar

x < y

example

3 < 4 // true
Copy the code

Less than or equal operator (<=)

The less than or equal operator returns true if the left-hand operand is less than or equal to the right-hand operand

grammar

x <= y

example

3< =4 // true
Copy the code

Equality operator

Equality operator

Basic instructions

The comparison operator converts two operands of different types and then performs a strict comparison.

When two operands are both objects, JavaScript compares their internal references to be equal if and only if their references refer to the same object (region) in memory; that is, they refer to the same address in stack memory.

x == y
Copy the code

Use case

 1= =1     // true
"1"= =1     // true
 1= ='1'    // true
 0= =false  // true
Copy the code

The unequal operator

Basic instructions

The unequal operator returns true only if the operands are not equal. If the two operands are not of the same type, JavaScript tries to convert them to an appropriate type and then compares them.

If two operands are object types, JavaScript compares their internal reference addresses only if they are not equal when referencing different objects in memory.

x ! = yCopy the code

Use case

1! =2     // true
1! ="1"    // false
1! ='1'    // false
1! =true   // false
0! =false  // false
Copy the code

Strict equality operator

Basic instructions

The consistency operator does not perform type conversions and returns true only if the operands are strictly equal

x === y
Copy the code

Use case

3= = =3   // true
3= = ='3' // false
var object1 = {"value":"key"}, object2={"value":"key"};
object1 === object2 //false
Copy the code

Strict unequal operator

Basic instructions

The inconsistent operator returns true if the operands are of unequal or different types

x ! == yCopy the code

Use case

3! = ='3' // true
4! = =3   // true
Copy the code

Conditional operator

Basic instructions

The conditional (ternary) operator is the only JavaScript operator that uses three operands. A condition is followed by a question mark. , if the condition is truthy, the expression A after the question mark will be executed; Expression A is followed by A colon (:), and if the condition is falsy, expression B after the colon is executed. This operator is often used as a shorthand form of an if statement.

condition ? exprIfTrue : exprIfFalse
Copy the code

parameter

  • conditionThe result is used as an expression for the condition
  • exprIfTrueIf the expressionconditionThe result of the calculation is Truthy (it andtrueIs equal to or can be converted totrue), then the expressionexprIfTrueIt’s going to be evaluated.
  • exprIfFalseIf the expressionconditionThe result of the calculation is Falsy (which can be converted tofalse), then the expressionexprIfFalseWill be executed.

Use case

In addition to false, possible expressions for false values include null, NaN, 0, empty string (“”), and undefined. If condition is any of the above, then the result of the conditional expression is the result of the exprIfFalse expression execution.

A simple example:

var age = 26;
var beverage = (age >= 21)?"Beer" : "Juice";
console.log(beverage); // "Beer"
Copy the code

A common use is to handle values that may be null:

function greeting(person) {
    var name = person ? person.name : "stranger";
    return "Howdy, " + name;
}
console.log(greeting({name: 'Alice'}));  // "Howdy, Alice"
console.log(greeting(null));             // "Howdy, stranger"
Copy the code

The assignment operator

Basic instructions

Assignment operators assign left operand values based on right operand values.

A simple assignment operator that assigns a value to a variable. To assign a value to multiple variables, you can use the assignment operator in chained form.

Operator: x = y
Copy the code

Use case

// Assuming the following variables
x = 5
y = 10
z = 25

x = y     // x is 10
x = y = z // x, y and z are all 25
Copy the code

Combination that

Every major arithmetic operator, and a few others, has a corresponding compound assignment operator. The basic assignment operator is equal (=), which assigns the value of its right-hand side to the left-hand side. That is, x is equal to y and I assign the value of y to x. Other assignment operators are usually short versions of the standard operators, as defined and exemplified below.

The name of the shorthand meaning
Assignment x = y x = y
Addition assignment x += y x = x + y
Traction Assignment x -= y x = x - y
To use a multi to assign a value x *= y x = x * y
Division Assignment x /= y x = x / y
Module assignment x %= y x = x % y
Exponentiation Assignment x **= y x = x ** y
Left Shift Assignment x <<= y x = x << y
Right Shift Assignment x >>= y x = x >> y
Unsigned right Shift Assignment x >>>= y x = x >>> y
Bitwise AND Assignment x &= y x = x & y
Bitwise XOR Assignment x ^= y x = x ^ y
Bitwise OR Assignment x |= y x = x | y

Comma operator

Basic instructions

The comma operator evaluates each of its operands (left to right) and returns the value of the last operand.

grammar

expr1, expr2, expr3...
Copy the code

parameter

expr1, expr2, expr3... Any expression.Copy the code

You can use the comma operator when you want to include multiple expressions where you expect an expression.


Use case

The for loop

Assuming a is a two-dimensional array with 10 elements per dimension, the following code increments/decrements two variables at a time using the comma operator. Note that the comma _ in the var statement is not the _ comma operator because it does not exist in an expression. In practice, though, that comma behaves much like the comma operator.

But more specifically, it is a special symbol in the VAR statement used to combine multiple variable declarations into one. The following code prints the diagonal elements of a two-dimensional array

for (var i = 0, j = 9; i <= 9; i++, j--) 
  document.writeln("a[" + i + "] [" + j + "] =" + a[i][j]);
Copy the code

Return after processing

Another example of using the comma operator is to process some operations before returning a value. As in the following code, only the last expression is returned, the others are simply evaluated.

function myFunc () {
  var x = 0;
  return (x += 1, x); // the same of return ++x;
}
Copy the code

Operator priority

See the MDN Operator_Precedence


Summary of today’s lesson



Today the mood

Today is mainly based on the search to carefully study the 3.5 operators in chapter 3, feel the combination of operators of the fierce place ~~~, feel very good, look at the MDN found that there are a lot of operators, but, the book did not write, temporarily did not learn, I hope to learn more tomorrow ~~~~

Recently, the article has been published with the prompt Request Entity Too Large. It has changed a lot of versions before it was successfully sent, which is very troublesome ~~~


This article is formatted using MDNICE