Home > Web Front-end > JS Tutorial > body text

Javascript core reading expressions and operators_Basic knowledge

WBOY
Release: 2016-05-16 16:14:25
Original
1220 people have browsed it

An expression is a phrase in JavaScript that the JavaScript interpreter will calculate to a result. The simplest type of expression commonly used in programs is variables. A variable name is also a simple expression, and its value is the value assigned to the variable.

Complex expressions are composed of simple expressions. For example, an array access expression consists of an expression representing an array, square brackets, and an integer expression. The result of the new expression they form is the value of the element at a specific position in the array. Same letter

The number call expression consists of an expression representing a function object and 0 multiple parameter expressions. The most common way to combine simple expressions into complex expressions is through operators.

This chapter (this article) will explain all javascript operators. It also explains expressions that do not involve operators (such as accessing array elements and function calls). Its syntax and programming style are very similar to the C language.

1. Element expression

The simplest expressions are "primitive expressions", which are the smallest units of expressions - they contain no other expressions. Primitive expressions in JavaScript contain constants or literals. Keywords and variables.
Direct quantities are constant values ​​that appear directly in the program. They look like:

Copy code The code is as follows:

               1.23 //Digital direct quantity
"hello" //String literal
                                                                                                                                                                                                                                                                        to
Some reserved words in JavaScript constitute primitive expressions

Copy code The code is as follows:
                true //Boolean value: true
                                                                                                                      false Null // Return a value: empty
This //returns the "current" object


Through the study in Chapter 3, unlike other keywords, this is not a constant, and the values ​​it returns in different places in the program are also different. The this keyword often appears in object-oriented programming. this returns the object of the square method. Finally, the third primitive expression is the variable


i //Return the value of variable i
sum //Return the value of sum
Undefined // is a global variable, unlike null, it is not a keyword


2. Initialization expressions for objects and arrays.

Object and array initialization are actually newly created objects and arrays. These initialization expressions are sometimes called "object literals" and "array literals". However, unlike Boolean literals, they are not primitive expressions because the members or elements they contain are subexpressions.

The syntax of the initialization expression of an array is very simple. Let’s start with the following

The initialization expression of the array is composed of a pair of square brackets and a list separated by commas. The initialization result is a newly created array. The elements of the array are the values ​​of a comma-separated expression.

[] //An empty array; leaving empty within [] means that the array does not have any elements

[1 2,3 4] //Array with two elements, the first is 3, the second is 7

An element-initialization expression in an array-initialization expression can be an array-initialization expression. In other words, expressions can be nested

var mat = [[1,2,3],[4,5,6],[7,8,9]];


The elements between the lists in the array literal can be omitted, and the empty spaces will be filled with undefined. For example, as follows:

var a=[1,,,,5]

Four of the elements are undefined. Leaving a comma at the end of the array literal will not create a new element with a value of undefined.

Object initialization expressions are very similar to array initialization expressions, except that the square brackets are replaced by curly braces. And each sub-expression contains a property name and a non-colon as a prefix.

Copy code The code is as follows:

var p = {x: 2.1,y: -3} //An object with two attribute members
            var q = {}; //Empty object
​​​​​​ q.x=2.1;q.y=-3; //The attribute members of q are the same as those of p

Object literals can also be nested, such as

Copy code The code is as follows:

var anh = {left:{x:2,y:3},
                                                                                                                                                                                                                                                                                                          
When JavaScript calculates the value of an object initialization expression, the object expressions will be calculated once each, and they do not have to contain constant values: they can be any JavaScript expressions. Likewise, the names of properties in object literals can be strings rather than identifiers. (Very useful when only reserved words or some illegal identifiers can be used as attribute names in that line)

Copy code The code is as follows:
          var side = 1;
          var square = {"left":{x:p.x,y:p.y},
             'right':{x:p.x side,y:p.y side}}

Chapter 6 and 7 will again discuss initialization expressions for objects and arrays.

3. Function expression

Function definition expression defines a javascript function. The value of the expression is this newly defined function. In a sense, function definition expressions can become function literals, and function expressions can be called "function literals." After all, object initialization expressions are also called "object literals." A typical function definition expression contains the keyword function, followed by a pair of parentheses. Within the parentheses is a comma-separated list containing 0 or more identifiers (parameter names). Then follow the JavaScript code segment (function body) wrapped in curly braces.

var square = function(x){ return x*x};

Function definition expressions can also contain the name of the function. Functions can also be defined via function statements instead of function expressions. More details will be described in Chapter 8.

4. Attribute access expression

Attribute access expression operation obtains the value of an object or an array element. JavaScript defines two methods for property access.

Copy code The code is as follows:
Expression . indentifier
Expression [expression]

The first way of writing is an expression followed by a period and an identifier. The expression specifies the object, and the identifier specifies the property to be accessed.

Chapter 2 is written using square brackets, and inside the square brackets is an expression (this method applies to objects and arrays). The second expression specifies the index of the property to be accessed or represents the index of the array element to be accessed. Here are some concrete examples

Copy code The code is as follows:
o.x //=>1x attribute of expression o
o.y.z //=>3 z attribute of expression o.y
                                                                                                                                                                                                                               . a[1] //=>4 The element of expression a with index 1
a[2]["1"]//=>6 The element with index 1 in expression a[2]
a[0].x //=>1: x attribute of expression a[0]

No matter which form of attribute access expression is used, expressions before "." and "[" will always be evaluated first. If the expression evaluates to null or undefined, the expression will throw a TypeError exception because neither value can contain any properties. If the operation result is not an object or array, JavaScript will convert it to an object (Chapter 3, Section 6)

Although .identifier is simpler to write, it should be noted that this method is only applicable when the attribute name to be accessed is a legal identifier. And need to know the name of the attribute to be accessed. If the property name is a reserved word or contains spaces and punctuation, or is a number (for arrays), it must be written in square brackets. When the attribute name is a value obtained by an operator rather than a fixed value, square brackets must be used. (Chapter 6, verse 2, section 1)

5. Movement expression

The invocation expression in JavaScript is a grammatical representation of calling (or executing) a function or method. It starts with a function expression that refers to the function to be called. A function expression is followed by a pair of parentheses containing a comma-separated list of parameters. There can be 0 or more parameters.

                            f(0) //f is a function expression: 0 is a parameter expression.
                Math.max(x,y,z) //Math.max is a function; x, y and z are parameters
              a.sort() //a.sort() is a function, it has no parameters.
When an expression is called for evaluation, the function expression is first evaluated, and then the parameter expression is evaluated to obtain a set of parameter values. If the value of the function expression is not a callable object, a type error exception is thrown. Then the values ​​of the parameters are assigned to the formal parameters in turn, which are defined when the function is defined. Next execute the function body. If the function uses the return statement to give a return value, then the return value is the value of the entire calling expression. Otherwise, the value of the calling expression is undefined. Details of function calls—including what happens when the number of formal parameter expressions does not match the number of actual parameters in the function definition—will be explained in detail in Chapter 8. .

Any call expression contains a pair of parentheses and the expression before the left parenthesis. If the expression is a property access expression, then the call is called a "method inviation". When the function body is executed in a method call, the objects and arrays used as attributes to access the body are the points of this in the calling method. This property allows a function (whose OO name is a "method") to call its host object in the object-oriented programming paradigm (more on this in Chapter 9).

6. Object creation expression

Object creation expression creates an object and calls a function (constructor) to initialize the object's properties. Object creation expressions are very similar to function call expressions, except that there is an additional keyword new:

before the object creation expression.

new Object()
new Point(2,3)
If the object creation expression does not require any parameters to be passed to the constructor, then this pair of parentheses can be omitted. More details of the constructor will be explained in Chapter 9

new Object
          new Point

7. Operator overview

Operators in JavaScript are used for table expressions, comparison expressions, logical expressions, assignment expressions, etc.
It should be noted that most operators are represented by punctuation marks, such as delete and instanceof. Whether they are keyword operators or symbolic operators, the operators represented are all regular operators, and their syntax is very concise and comprehensive.
Sorted by the precedence of subscript operators, the precedence of the operator is higher than the precedence of the latter operator. Operators separated by horizontal scalars have different precedence.
A represents the associativity of the operator.
L from left to right or R (from right to left)
The list of header N represents the number of operands.
The type indicates the type of the expected operands, and the result type of the operator (after the "→" symbol)

Operator Operation A N Type
Pre/Post Increment R 1 lval→num
-- Decrease before and after R 1 lval→num
- Reverse R 1 num→num
Convert to number R 1 num→num
~ Bitwise negation R 1 int→int
! Logical NOT R 1 bool→bool
delete Delete attributes R 1 lval→bool
typeof Detect operation type R 1 any→Str
void Return undefined value R 1 any→undef
*,/,% Multiply and divide to find the remainder L 2 num, num→num
, - Add, subtract L 2 num, num→num
String concatenation L 2 str, str→str
<< Left shift L 2 int, int→int
>> Shift right L 2 int, int→int
>>> Unsigned right shift

L

2 int, int→int
<, <=, >, >= Compare numerical order L 2 num,num→bool
<, <=, >, >= Compare the order in letters L 2 str, str→bool
instanceof Test object class L 2 obj, func→bool
in Test if the attribute exists L 2 str,obj→bool
== Judgment of equality L 2 any, any→bool
! = Unequal judgment L 2 any, any→bool
=== Judge identity L 2 any, any→bool
! == Judge non-identity L 2 any, any→bool
& Bitwise AND L 2 int, int→int
^ Bitwise XOR L 2 int, int→int
| Bitwise OR L 2 int, int→int
&& Logical AND L 2 any, any→any
|| Logical OR L 2 any, any→any
?: Conditional operator R 3 bool, any, any→any
= Variable assignment or object property assignment R 2 lval, any→any

*= /= %= = -= &=

^= |= <<= >>= >>>=

Operation and assignment R 2 lval, any→any
,

Ignore the first operand,

Return the second operand.

L 2 any, any→any

i. Number of operands

Operators can be classified by the number of operands.

Most operators in JavaScript are binary operators, combining two expressions into a slightly more complex expression.
JavaScript also supports some unary operators, which convert one expression into another slightly more complex expression. The "-" operator in the expression -x is a unary operator. is to take the negative value of x.
JavaScript supports a ternary operator: the conditional judgment operator "?:", which combines three expressions into one expression

ii. Operand type and result type

Some operators can be used on any data type, but you are still expected to operate on data of a specified type.

iii. Left value

The assignment operator and a few other operators in the table expect their operands to be of type lval, lvalue being an archaic term. It means "an expression can only appear on the left side of an assignment operator". In JavaScript, variables, object properties, and array elements are all lvalues. The ECMAScript specification allows scoped built-in functions to return an lvalue, but defined functions cannot.

iiii. Priority of operators

In the above table, the operators shown are ordered from high to low priority, and a group of operators within each horizontal dividing line have the same priority. Operator precedence controls the order in which operators are executed. Operators with higher precedence (top of the table) are always executed before operators with lower precedence (bottom of the table).

Look at the following expression

w=x y*z;
The multiplication operator "*" has a higher priority than the addition " ", so the multiplication is executed first. Then, since the assignment operator "=" has the lowest precedence. Therefore, the assignment operation is performed after the expression on the right-hand side has been evaluated.

The precedence of operators can be written using parentheses. The above expression can be written like this.

w = (x y) * z;
Note that property access expressions and call expressions have higher precedence than all operators in the table.

typeof my.Function[x](y)
Although typeof is one of the highest precedence operators, typeof is also executed after two property accesses and function calls.

In fact, if you are really not sure about the precedence of the operators you are using, the easiest way is to use parentheses to force the order of operations. There are some important rules to remember: multiplication and division are higher than addition and subtraction, and assignment operations have very low priority and are usually executed last.

iiiiii. Associativity of operators

In this section of the table, the column titled A describes the nodularity of the operator. L means to combine from left to right, R means to combine from right to left. Tuberculity specifies the order of operations in multiple operator expressions with the same precedence.

For example, subtraction operations are performed associatively from left to right.

Copy code The code is as follows:

w = x - y - z

Same as this code:

Copy code The code is as follows:

w = ((x - y) - z)

Conversely speaking, the following expression:

Copy code The code is as follows:

x = ~-y;
w = x = y = z;
q=a?b:c?d:e?f:g;

Exactly the same as this code

Copy code The code is as follows:

x=~(-y);
w=(x=(y=z));
q=a?b:(c?d:(e?f:g))

Because unary operators, assignments and ternary conditional operators all have right-to-left associativity.

iiiiiii. Order of operations

The precedence and associativity of operators specify their order of operations in the assignment expression, but do not specify the order of operations in the calculation process of subexpressions. JavaScript always evaluates expressions strictly from left to right, for example:

In the expression w=x y*z, the expression w will be calculated first, and then x, y and z will be calculated. Then, the value of y is multiplied by z, and the value of x is added. Finally, the variable or attribute pointed to by its expression w. Adding parentheses to an expression changes the relationship between multiplication, addition, and assignment operations. But the order from left to right will not change.

8. Arithmetic expressions

This section covers operators that perform arithmetic calculations, as well as arithmetic operations on operands. The multiplication, division and subtraction operators are very simple. The addition operation is a separate section, because the addition operator can operate the concatenation of strings, and its type conversion is somewhat special.

The basic arithmetic operators are *, /, %, , -. Except for addition, other operators are very simple. They just convert the operators into numbers when necessary, and then calculate the product, quotient, remainder (modulus) and difference. All those operations that cannot be converted to numbers will be converted to NaN values. If the operand (or conversion result) is a NaN value, the result of the arithmetic operation is also NaN

The operator "/" divides the second operand by the first operand, if you have used programming languages ​​that distinguish between integers and floating point numbers. Then when dividing an integer by an integer, the desired result is also an integer. All numbers in JavaScript are of floating point type, and the results of division operations are also of floating point type. For example, the result of 5/2 is 2.5, not 2. The result of an operation that divides by 0 is positive infinity or negative infinity. And the result of 0/0 is NaN. All these operations are error-free.

The operator "%" calculates the modulus of the first operand to the second operand. In other words, it is the remainder of the first operand divided by the second operand. The sign of the result remains the same as the sign of the first operand (the dividend). For example, the result of 5%2 is 1, and the result of -5%2 is -1.

The operands of the remainder operator are usually integers, but they also work with floating point numbers. 6.5%2.1 turns out to be 0.2. (0.19999999999999973)

i. " " operator

The binary addition operator " " can add two numbers, and can also perform string concatenation operations:

Copy code The code is as follows:

1 2 //=> 3
"hello" "" "there" // =>"hello there"
"1" "2" //=>"12"

When both operands are numbers or strings, the calculation result is obvious. However, for other cases, some necessary type conversions must be performed. And the behavior of the operator depends on the result of the type conversion. Technically speaking, the addition operator behaves like this:

If an operand is an object, the object will be converted into a primitive class value following the conversion rules of objects to primitive values ​​(refer to Chapter 3, Section 8, Section 3). Dates are converted by the toString() method of objects, and other objects are converted by the valueOf() method (if the valueOf() method returns a primitive value). Since most objects do not have a valueOf() method available, they will perform capture and replacement through the toString() method
After converting the object to a primitive value, if one of the operands is a string, the other operand is also converted to a string. Then perform string concatenation.
Otherwise, both operands are converted to numbers (or NaN) and the addition operation is performed.
Here are some examples

Copy code The code is as follows:

1 2 //=>3 Addition
"1" "2" //=>"12" String concatenation
"1" 2 //=>"12"The number is converted into a string and then the string is connected
                                                                                                                                                                                                                 1 {} //=>"1[object object]": Convert the object to a string and perform string concatenation
                   true true //=>2 Convert the Boolean value to a number and then add it
                 2 null //=>2 null is converted to 0 and then added
                  2 undefined //=>NaN undefined is converted to NaN for addition

Finally, something special to note. When the addition operation is used with strings, the effect of addition on the order of operations must be considered. In other words, the result of the operation depends on the order of operations of the operators, such as

Copy code The code is as follows:

               1 2 "bmice" //=> "3 bmice"
              1 (2 "bmice") => "12bmice"

ii. Unary operator

Unary operators act on a single operand. and produce a new value. In JavaScript, unary operators have high precedence and are right-associative. This section describes the unary operators ( ,-, and --), which convert operations to numbers when necessary. It should be noted that - is a unary operator and a binary operator,

One dollar addition

The unary addition operator converts the operand number to a number (or NaN) and returns the converted number. If the operand itself is a number, this number is returned directly.

One dollar subtraction-

When the - sign is used as a unary operator, it will convert the operands into numbers as needed, and then change the sign of the operation result.

increment

The increment " " operator performs an increment (1) operation on its operand, which is an lvalue (variable, array element or object attribute). Operators convert operands to numbers. Then add 1 to the number, and reassign the added value to a variable, array element, or object property.

Increment The return value of an operation depends on the position of its operands.

When the operator precedes the operand, it is called the "pre-increment" operator. It performs incremental calculations on the operand and returns the calculated value.

When the operator is after the operand, it is called a "post-increment" operator. It performs incremental calculation on the operand, but returns an unincremented value. Such as

var i = 1,j = i //The values ​​​​of i and j are both 2
              var i = 1,j = i; //i is 2, j is 1
It should be noted that, just like x and sum x=x 1, the " " operator never performs string concatenation, it always converts the operand to a number and increments it by 1. If x is the string "1" , the result of x is the number 2, and x 1 is the string "11"

The operation method of decrement and increment is the same. It converts the operand into an array and then decreases it by 1.

iii. Bit operators

Bitwise operators can perform lower-level bitwise operations on binary data represented by numbers. Although they are not traditional pure mathematical operations, they are classified here as arithmetic operators because they operate on numeric types and return numbers. These operators are uncommon in JavaScript. (Not described here, please refer to Baidu for details~-~)                          

9. Relational expressions

This section describes the relational operators of JavaScript. The relational operators are used to test the relationship between two values ​​(equal, less than or "is an attribute of..."), and return true and false depending on whether the relationship exists. .Relational expressions always return a Boolean value. Relational expressions are usually used in if while or for statements (Chapter 5) to control the execution flow of the program.

The next few sections will talk about equality and inequality operations, comparison operators and the other two relational operators in and instanceof in JavaScript

iEquality and inequality operators

The "==" and "===" operators are used to compare whether two values ​​are equal. The two operators allow any type of operator. Returns true if they are equal, otherwise returns false. "===" is also called the strict equality operator (sometimes called the identity operator), which is used to detect whether two operands are strictly equal. The "==" operator is called the equality operator, which is used to check whether two operands are equal. The definition of equality here is loose and allows type conversion.

Javascript supports "=", "==", "===" operators, you should understand the difference between (assignment, equality, identity) operators. And use it with care in programming. To reduce confusion, "=" should be called "getting or assigning", "==" should be called "equality", and "===" should be called "strict equality".

The "!=" and "!==" operator rules are "==", the negation of the "===" operator, "!" is a Boolean non-operator, we will "!=", " !==" is called inequality, not strict equality

The comparison of JavaScript objects is a reference comparison, not a value comparison. The object is equal to itself, but neither the person nor the object is equal. If two objects have the same number of properties, the same property names and values, they are still not equal. Even if the array elements at corresponding positions are equal, the two arrays are also unequal.

The strict equality operator "===" first calculates the value of the operand, and then compares the two values ​​without any type conversion.

If two value types are not the same, they are not equal
If both values ​​are null or undefined, they are not equal
If both values ​​are Boolean true or false, then they are equal
If one of the values ​​is NaN, or both values ​​are NaN, then they are not equal. NaN is not equal to other values, including itself.
Two values ​​are equal if they are numbers and equal. If a value is 0 and a value is -0, they are also equal.
Two values ​​are equal if they are strings and contain exactly the same 16 digits in corresponding bits (see Chapter 3, Section 2). If they are different in length or content, they are not equal. Two strings may function exactly the same and display the same characters, but have 16-bit values ​​without encoding. JavaScript does not perform standard conversion to Unicode, so such strings are passed through "===" and "==" The comparison results of operators are also not equal. String.localeCompare() in Part 3 provides another way to compare strings.
Two reference values ​​are equal if they point to the same object, array, or function. If they point to different objects, they are not equal, even though both objects have exactly the same properties.
The equality operator "==" is similar to the identity operator, but the equality operator comparison is not strict. If the two numbers are not of the same type, the equality operator attempts some type conversion and then compares them.

If the two operation types are the same, the comparison rules are the same as the equality operator above. If strictly equal, the comparison results are equal. If they are not strictly equal, the comparison results in unequal.
If two operation types are different, the "==" equality operator will also consider them equal. Detecting equality will follow the following rules and type conversions:
If one type is null and one is undefined, then they are equal
If one value is a number and the other is a string, first convert the string to a number and then use the converted values ​​for comparison.
If a value is true, it is converted to 1 and compared. If a value is false, it is converted to 0 for comparison.
If one value is an object and the other value is a number or string, use the conversion rules of the method in Chapter 3, Section 8, Subsection 3 to convert the object to a primitive value, and then compare. The object is converted to a primitive value through the toString() method or the valueOf() method. The built-in classes in the core of the JavaScript language first try to use valueOf() and then try to use toString(). Except for the date class, the date class can only be converted through toString(). Objects that are not part of the core JavaScript language are converted to primitive values ​​using methods defined in the implementation.
Comparisons between other different types are not equal
Here is a small example of equality

"1" == true
This expression evaluates to true, which indicates that values ​​of completely different types compare equal. The boolean true is first converted to the number 1 before the comparison is performed. Next, the string "1" will also be converted to the number 1, because the values ​​of the two numbers are equal, so the result is true.

ii. Comparison operators

Less than (<)

If the first operand is less than the second operand, the "<" operation result is true, otherwise it is false

Less than or equal to (<=)

Greater than (>)

Greater than or equal to (>=)

....(not detailing the meaning)

The operands of comparison operators may be of any type. However, only numbers and strings can actually perform comparison operators, so any operands that are not numbers or strings will undergo type conversion. The type conversion rules are as follows:

If the operand is an object, it is converted to a primitive value according to the conversion rules described in the lock description in Chapter 3, Section 8, Subsection 3: If valueOf() returns a primitive value, then use this primitive value directly. Otherwise the conversion result of toString() is used for comparison.
After converting the pair to a primitive value, if both operands are strings, then the two strings will be compared in alphabetical order. The "alphabetical order" mentioned here is what makes up the two strings. Index order of 16-bit Unicode characters.
After the object is converted to a primitive value, if at least one operand is not a string, both operands will be compared numerically. 0 and -0 are equal. Infinty is larger than any other number (except infinty itself), and -infinty is smaller than any number (except itself.) If an operand (or converted) is NaN, the comparison operator always returns false
For numeric and string operators, the plus operator behaves differently than the comparison operator. The former prefers strings and performs string concatenation if one of its operands is a string. Comparison operators prefer numbers only when both operands are strings. String comparison will be performed.

Copy code The code is as follows:

1 2 //=>3 addition, the result is 3
"1" "2" //String concatenation, the result is "12"
"1" 2 //String concatenation, 2 is converted to "2", the result is "12"
                11 < 3 //Number comparison, the result is true
"11" < "3" //String comparison, the result is true
"11" < 3 //Comparison of numbers, "11" is converted to 11, and the result is true
"one" < 3 //Number comparison, "one" is converted to NaN, the result is false

Finally, it should be noted that the "<=" and ">=" operators do not rely on the equality operator and strict equality comparison rules when determining equality. In contrast, the less than or equal operator is simply "not greater than" and the greater than or equal operator is simply "not less than". There is only one exception, when one of the operands (after conversion) is NaN, all four comparison operators will return fasle.

iii.in operator

The

in operator expects its left operand to be a string or convertible to a string, and its right-hand side to be an object. If the object on the right has a property name named the left operand value, then the expression returns true. For example,

Copy code The code is as follows:

var point = {
                       x: 1,
                   y: 1
                                                                                                                                          // Define an object
"x" in point //=>true The object has a property named x
"z" in point //=>false The object's unnamed attribute is z
"toString" in point // =>true The object inherits the toString method

var data = [7, 8, 8]
"0" in data //=>true array contains 0
                                                                                                                                                                                                                                             1 in data //=>true Numbers converted to strings
                 3 in data //=>fase There is no element with index 3

iiii.instanceof operator

The instanceof operator expects the left operator to be an object and the right operand to indicate the class of the object. If the object on the left is an instance of the class on the right, the expression returns true; it is responsible for returning false. Chapter 9 will talk about it. Classes of JavaScript objects are defined by initializing their constructors. In this case, the right operand of instanceof should be a function. For example:

Copy code The code is as follows:

               var d = new Date(); //Construct a new object
               d instanceof Date; //The calculation result is true, d is created by Date()
               d instanceof Object //The calculation result is true, all objects are instances of Object
                d instanceof Number //The calculation result is false, d is not a Number object
                 var a = [1,2,3] //Array literal creates array
a instanceof Array //The calculation result is true a is an array
              a instanceof Object //true All arrays are objects
               a instanceof RegExp //fasle array is not a regular expression

It should be noted that all objects are instances of Object. When checking whether an object is an instance of a class through instanceof, this judgment is also called "superclass" detection. If the left operation object of instanceof is not an object, instanceof returns false. If the right-hand operation is not a function, an exception of typewrong is thrown.

In order to understand how the instanceof operator works, you must first understand the "prototype chain". The prototype chain, as the inheritance mechanism of JavaScript, will be described in detail in Chapter 6, Section 2, Section 2.

In order to calculate the expression o instanceof f, JavaScript PenXian first calculates f.prototyoe, and then queries o in the prototype chain. If found, then o is an instance of f (or the parent class of f), then true is returned. Otherwise false

10. Logical expression

Logical operators "&&", "||", and "!" perform Boolean arithmetic operations on operations. They are often used together with relational operators. Logical operators combine multiple relational expressions to form a more complex one. expression.

i. Logical AND

The "&&" operator can be understood at three different levels. The simplest understanding is that when the operands are both Boolean values, "&&" performs a Boolean AND (AND) operation on two Boolean values, only when the first operand and the second operand are both true. , it returns true. If one of the operands is false, then it returns false.

"&&" is used to connect two relational expressions

x == 0 && y == 0; //Return true only when x and y are both 0
Relational expressions always return true or false, so when used like this, "&&" itself also returns true or false. Relational operators have higher precedence than "&&" (and "||"), so expressions like this can be safely written without the need for parentheses.

The "&&" operand is not necessarily a Boolean value. Recall that some values ​​can be regarded as "true values" and "false values". (As in Chapter 3, Section 3, false values ​​are: false null undefined 0 -0 NaN and "", all and other values ​​including all objects are true values). The second level of understanding of "&&" is that "&&" can perform a Boolean AND (AND) operation on true and false values. If both operands are true, then a true value is returned; otherwise, at least one operand is false. Any time a Boolean value is used in JavaScript, the expression statement will treat it as a true or false value, so in fact "&&" does not always return true and false. But it is not a big deal.

It should be noted that the above mentioned operator returns "true value" and "false value", but it does not explain what the "true value" or "false value" is. For this reason, we will discuss in depth. Understanding of the third layer of "&&". The operator first calculates the value of the left operand, that is, it first calculates the expression on the left side of "&&". If the calculation result is a false value, then the result of the entire expression must be a false value, so "&&" simply returns the left operand. The value of the operation, without calculating the operand on the right.

Copy code The code is as follows:

var o = {
                    x: 1
            };
          var p = null;
o && o.x; //=>1 : 1:0 is a true value, so the return value is o.x
                p && p.x //= null: p is a false value, so it is returned without calculating p.x

This is crucial to understand that "&&" may not calculate the right operand. In the above code, the value of variable P is null, and if p.x is calculated, an exception error will be thrown. Therefore, only p p.x

is calculated only if it is a true value (cannot be null or undefined)

The behavior of "&&" is sometimes called "short circuiting", and we often see a lot of code taking advantage of this to conditionally execute code. For example, the following two codes are equivalent

Copy code The code is as follows:

If (a == b) stop (); // Only when you only a == B, you can transfer stop ()
(a == b) && stop(); //Same as above

In general, be careful when the expression on the right side of "&&" has side effects (assignment, increment, decrement, and function call expressions). Because the execution of these expressions with side effects depends on the calculation result of the left operator mouse.

Although "&&" can perform some complex expression operations according to the understanding of the second and third levels, in most cases, "&&" is only used to perform Boolean calculations on true and false values.

ii. Logical OR (||)

The "||" operator performs a Boolean OR (OR) operation on two operands. If one of the operands is true, it returns true, if both operands are false, it returns false.

Although the "||" operator just does a simple Boolean OR (OR) operation in most cases, like "&&", it also has some more complex behaviors. It first calculates the value of the first operand, and That is to say, the expression on the left is first calculated. If the calculation result is true, the true value is returned. Otherwise, the second value is calculated.

Like "&&", you should avoid the right operand containing some expressions with side effects, unless you explicitly use an expression with side effects on the right side, and the expression on the right side may not be evaluated.

The most common way this operator is used is to select the first true-valued expression from a set of alternative expressions.

Copy code The code is as follows:

​​​​ //If max_width has been defined, use it directly. Assignment looks for max_width
in the preferences object ​​​​ //If it is not defined, a hard-coded constant is used.
var max =max_width || preferences.max_windth || 500;

This common usage is usually within the body of a function to provide default values ​​for parameters.

Copy code The code is as follows:

//Copy the successful attributes of o to p and return p
             function copy(o, p) {
                    p = p || {}; //If no object is passed to parameter p, a newly created object is used.
//Main logic in the function body

iii. Logical NOT (!)

The "!" operator is a unary operator that is placed before a single operand. Its purpose is to negate the Boolean value of the operand.

Different from the "&&" and "||" operators, the "!" operator first converts its operand to a Boolean value (refer to the rules of appeal in Chapter 3), and then negates the Boolean value. That is, "!" always returns true and false. Moreover, the Boolean value of a value can be obtained by using two logical NOT operations: (!!x, refer to Chapter 3, Section 8, Section 2)

"!" has a high priority and is closely tied to the operands. If you want to compare p && q, you need garden brackets! (p && q). The following code:

Copy code The code is as follows:

                 !(p && q) === !p || !q
                 !(p || q) === !p && !q

For any values ​​of p and q, these two expressions always hold.

11. Assignment expression

Javascript uses the "=" operator to assign values ​​to variables or attributes, for example:

Copy code The code is as follows:

                i = 0 //Set variable i to 0
                 o.x = 1 //Set the attribute x of object o to 1

The "=" operator expects its left operand to be an lvalue: a variable or object property (or array element), and its right operand can be any value of any type. The value of the assignment expression is the value of the right operand. A side effect of an assignment expression is that the value of the right operand is assigned to the variable or object property on the left. In this case, subsequent references to this variable and object's properties will get this value.

Although the value of an assignment expression is very simple, sometimes you will see some complex expressions containing assignment expressions. For example: put assignment and detection operations in one expression:

Copy code The code is as follows:

(a = b) == 0

If this is the case, you should clearly know the difference between "=" and "=="! , it should be noted that "=" has a very low priority. Usually when an assignment statement is used in a long expression, garden brackets need to be added to ensure the correct order of operations.

The associativity of assignment operators is from right to left. That is to say, multiple assignment operators appear in an expression, and the order of operations is also from right to left. Therefore, multiple variables can be assigned in the following ways .

Copy code The code is as follows:

         i=j=k=0; //Initialize the three variables to 0

Assignment operation with operation:

In addition to regular assignment operations, JavaScript also supports other assignment operators, which connect assignment operations to other operators. Provide a faster calculation method. For example, the = operator performs the addition operator and assignment operation, the following expression:

total = salaes_tax;
Equivalent to the following expression

total = total salaes_tax
The operator "=" can act on numbers or strings. If its operation is a number, it will perform addition and assignment operations; if it is a string, it will perform string concatenation and assignment operations.

This type of operators also includes, "-=","*=","&=", etc., as shown in the following table of assignment operators

operator example Equivalent to
= a =b a=a b
-= a-=b a=a-b
*= a*=b a=a*b
/= a/=b a=a/b
%= a%=b a=a%b
<<= a<<=b a=a< >>= a>>=b a=a>>b
>>>= a>>>=b a=a>>>b
&= a&=b a=a&b
|= a|=b a=a|b
^= a^=b a=a^b
In most cases, the expression is

a op =b
The op here represents an operator, and this expression is equivalent to

a =a op b
In the first line, the expression a is evaluated once, and in the second line, the expression a is evaluated twice.

The two are not equivalent only if a contains expressions with side effects (such as function calls and assignment operations). The following two expressions are not equivalent

Copy code The code is as follows:

              data[i] *= 2;
              data[i] = data[i] * 2

12. Expression calculation

Like many interpreted languages, JavaScript can also interpret and run a string composed of JavaScript source code and generate a value. JavaScript uses the global function eval() to complete this work.

eval("3 2") //=>5
Dynamically determining strings in source code is a powerful language feature that is rarely necessary to apply in practice. If you use eval(), you should carefully consider whether you really need it.

The following reduces the basic usage of eval(), and introduces two methods of strictly using it. From the perspective of code optimization, these two methods have the least impact on the original code.

i.eval (eval() is a function, but it has been treated as an operator.)

eval() has only one parameter. If the parameter passed in is not a string, it returns this parameter directly. If the parameter is a string, it will compile the string as JavaScript (parse). If the compilation fails, a syntax error (SyntaxError) will be thrown. If the compilation is successful, this code will be executed and the value of the last expression or statement in the string will be returned. If the last expression has no statement or value, undefined will eventually be returned. If the string throws an exception, the exception passes the call to eval()

The most important thing about eveal() is that it uses the variable scope environment of the calling it, that is, it looks up the value of the variable and defines new variables and functions in the same way as the code in the local code scope. . If a function defines a local variable x and then calls eval("x"), it will return the value of the local variable. If it calls eval("x=1"), it changes the value of the local variable. If the function calls eval("var y=3;") it declares a new local variable y. Similarly, a function can declare a local function through the following code:

eval("function f(){return x 1;}");
If eval() is called in the top-level code. Of course it will act on global variables and global functions.

ii. Global eval()

eval() has the ability to change local variables. This is a big problem for the javascript optimizer. However, as a stopgap measure, javascript does not do what the line that calls the eval() function does. Not much optimization. But how does the JavaScript interpreter work when the script defines an alias and calls it with a name? To simplify the JavaScript interpreter. The ECMAScipt3 standard stipulates that no interpreter is allowed to assign aliases to eval(). If eval() is called using another alias, an EvalError exception will be thrown.

Actually, most implementations don't do this. When called through an alias, eval() will execute its string as top-level global code. Executing code may define new global variables and global functions. The executed code may define new global variables and global functions, or assign values ​​to global variables. However, local variables in the calling function cannot be modified or modified, so this will not affect code optimization within the function.

ECMAScript5 opposes the use of EvalError and standardizes the behavior of eval(). "Direct eval", when the eval() function is called directly using the unqualified "eval" name, it always branches within its context scope. Other indirect calls use global functions as their context scope. And cannot read, write, define local variables and functions. Here is a code example:

Copy code The code is as follows:

var geval = eval; //별칭을 사용하여 eval을 호출하면 전역 평가가 됩니다
          var x = "전역",
                   y = "global" //두 개의 전역 변수
              function f() { //함수 내에서 실행되는 로컬 평가
​​​​​​​​ var                    eval("x = 'changed';") // eval은 지역 변수의
을 직접 변경합니다. 반품             }
             function g() { //이 함수는 전역 평가를 실행합니다
                    var y = "local" //로컬 변수가 정의됨
                   geval("y = 'changed';") //지역 변수 값을 간접적으로 변경함
Return y; // 변경되지 않은 지역 변수로 돌아갑니다
            }
                   console.log(f(), x) //로컬 변수가 변경되었으며 출력 로컬이 전역으로 변경되었습니다.
                console.log(g(), y) //전역 변수가 변경되었습니다. 출력 로컬 globalchanged


13. 기타 운영자.

Javascript는 기타 다양한 연산자를 지원합니다.

i.조건연산자(?:)

조건 연산자는 JavaScript의 유일한 삼항 연산자입니다. 일반적으로 이 연산자는 "?:"로 작성됩니다. 이 연산자에는 세 개의 피연산자가 있습니다. 첫 번째 피연산자는 "?" 앞에 있고 두 번째 피연산자는 ":" 사이에 있습니다. 세 번째 피연산자는 ":" 이후입니다(예:

).

x > 0 ? x : -x; //x의 절대값 찾기

조건부 연산자의 피연산자는 모든 유형이 될 수 있습니다. 첫 번째 피연산자는 부울 값으로 처리됩니다. true인 경우 두 번째 피연산자가 평가되어 결과가 반환됩니다. 할당 첫 번째 값 피연산자가 false이면 세 번째 피연산자가 평가됩니다. 그리고 계산 결과를 반환합니다. 두 번째 및 세 번째 피연산자는 항상 그 중 하나로 평가됩니다. 두 가지를 동시에 하는 것은 불가능합니다. 실제로 if 문(5.4.1)을 사용하여 동일한 효과를 얻을 수 있습니다. "?:" 연산자는 단지 약식 형식을 제공합니다. 다음은 변수 정의 여부를 결정하는 "?:"의 일반적인 사용 시나리오입니다. 정의되어 있으면 기본값이 사용됩니다.


grett = "hello"(사용자 이름 ? 사용자 이름: "3");


아래 코드와 동일하지만 위 코드가 더 간결합니다

          grett = "안녕하세요";
&N
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!