JavaScript Advanced Programming (3rd Edition) Learning notes 4 JS operator and operator _ basics

Source: Internet
Author: User
Tags arithmetic arithmetic operators bitwise bitwise operators logical operators md5 encryption numeric value tidy
In ECMAScript, there are very rich operators and operator, in this article will be the usual classification to slightly tidy up, but before sorting, first explain:

1, although the title is the operator and operators, however, in my opinion, there is not much need for strict distinction, in English, it seems to be a operator to express, so in the following I may be mixed. Even some of the categories that are not part of the operators and the operator, I also tidy up here as long as I feel necessary.

2, for the precedence of operators, you do not need to remember one by one-I believe you know the simplest "multiplication and division, then add and subtract", as for the other, if you are not sure, with parentheses. In ECMAScript, the same precedence is left-to-right operations.

3, for some general-purpose operators, such as the commonly used arithmetic operators (+-*/), I would simply enumerate and not expand, but note that it is not important to say that these generic operators are even in a very basic position, but I think you should already be familiar with There's no need to spend time stressing here.

4, then, what is the focus of attention here? Some of the more specific operators in ECMAScript, or some of the places I think are worth the time to emphasize.

Operators and operators

Category Operator Describe Description
Unary operator ++ Self-Increasing 1

1, since the increase (minus) there are two types of front and back, before the first self-increase (minus) and then participate in other operations, after the first participation in other operations and then self-increase (minus).

2, in the ES, self-increasing (minus) is not only applicable to integers, they can be used for arbitrary values, for values that are not of type number, are implicitly converted to number by the rules in the previous article, and then are added (subtract), and the variable types become number types.

-- Self minus 1
+ One dollar Plus The most important application of unary Plus is to convert the operand to number type, which is equivalent to calling numbers () conversion.
- One dollar minus One-dollar subtraction is based on a unary plus and then the opposite number.
Arithmetic operator + Add

1, in addition to plus (+), if the operand is not the number type, it automatically calls the numbers () converted to the Type No.

2, for addition and subtraction (+-), except as an arithmetic operator. It can also be used as a unary operator (see above). Of course, because of the overload of the plus sign (+) in string operations, it can also be used to connect any number (a string), which is also the 1th reason to add (+), which, when it contains a value other than number type, converts all operands to strings.

3, unlike the General Class C language, in Es, except (/) and modulo (%) does not distinguish between integers and floating-point numbers, such as 5/2 = 2.5 instead of 2,5.3% 3 = 2.3 instead of 2.

4, any operation, as long as the operand contains Nan, the result is Nan. However, it is not the result of Nan that must have an operand of Nan, for example 0/0 also returns Nan.

5, for the operation containing infinite infinity, the provisions are more, here is not listed, you can refer to the original book, or test.

- Reducing
* By
/ Except
% Take the mold
logical operators

(Boolean operator)

! Logical non

First, convert the operand to a Boolean value, and then reverse. can use double non!! Converts a numeric value to the corresponding Boolean value.

&& Logic and

1, when the corresponding Boolean value of two operands is true, return True

2. Short circuit: When the corresponding Boolean value of the first operand is false, it returns false directly and no second operand is evaluated. This is often used to determine whether a variable (attribute) has a definition, such as:
If (object && object.name && object.name = ' Linjisong ') {}
Here will first judge the existence of the object, does not exist will not parse object.name to prevent the occurrence of errors, the same, and only object.name exist, to compare this value.

| | |   Logical OR

1, returns true if at least one of the corresponding Boolean values of two operands is true

2, Short circuit: Returns true directly when the corresponding Boolean value of the first operand is true. The second operand is not evaluated again.

3, logic, or, in addition to general judgments, is often applied in situations where a default value is provided, such as:

function Fn (obj) {
obj = obj | | {};
}

If you call fn without passing in obj, the obj is automatically assigned to undefined, and then an empty object {} is assigned to obj because the corresponding Boolean value for undefined is false, and if the call passes into obj, Because the Boolean value of any object is true, the following {} is not taken, thus achieving the effect of giving obj a default value of {}. The

method is also applied to several relatively independent files in large JS libraries:
//jslib
var jslib;
File1
(function (jslib) {
Jslib = Jslib | | {};
}) (jslib);

//file2
(function (jslib) {
Jslib = Jslib | | {};
}) (Jslib);

The


uses this method to determine whether the jslib has been defined, regardless of which file is loaded first, and to provide a default value if not defined, so that a relatively independent module can be used regardless of the load order.

Relational operators

(comparison operator)

< Less than

1, as long as one operand is number or Boolean, converts two operands to the number type value (if conversion is required) to perform a numeric comparison.

2, string comparison, will compare character encoding values.

3, the operator is an object, call valueof () (if not, call ToString ()), and then compare the results by the above rules.

4, any number and Nan comparison returns false.

<= Less than or equal to
> Greater than
>= Greater than or equal to
== Equal

1, equal and unequal (= =,!=) when compared, implicit type conversions are required whenever necessary.

2, congruent and not congruent (= = =,!==) in the comparison, will not convert the type, if the type is inconsistent, directly for!==.

3, combined with 1, 2, you can know, a===b must have a==b, and a!=b must have a!==b.

!= Range
=== Congruent
!== Not congruent
Assignment operator = assigning values
Compound Arithmetic assignment operator Arithmetic operator plus = Corresponding arithmetic operators, with + =, =, *=,/=,%=
Compound Bitwise assignment Operator Bitwise operator PLUS = Corresponds to bitwise operators, with ~=, &=, |=, ^=, <<=, >>=, >>>=
Bitwise operator ~ Bitwise NON bitwise reverse, or return back code
& Bitwise AND Bitwise-ALIGNED, bitwise-operated, only two operator bits are 1 to return 1, otherwise the bit returns 0, and finally returns a combination of all the bit action results
| by bit or Bitwise-ALIGNED, bitwise-operated, only two operator bits are 0 to return 0, otherwise the bit returns 1, and finally returns a combination of all the bit action results
^ Per-bitwise XOR OR bitwise alignment, bitwise operation, two operation bit is not the same when return 1, otherwise the bit returns 0, and finally all the bit action result combination return
<< Move left The binary number shifts to the left and does not change the sign bit
>> Sign Right Move The binary number shifts to the right, and the high position fills with a bit
>>> No sign Right move Binary number to the right shift, directly to the right, for positive numbers, the same result and >>, for negative numbers, the binary complement of negative numbers as a positive binary code processing
String operators + string concatenation Equivalent to the concat () function, all operands are converted to strings before being concatenated. Note that once a string is created, it is not changed, and when a string connection is performed, there is an intermediate connection and destruction process in the background, which is why the old browser is slow to run in a large number of string concatenation operations.
+= string concatenation composite A+=b, equivalent to A=a+b.
Object operators . Property access Characters A simple object property accessor.
[] property or (Class) array access by [], you can access a property that has a variable or special character.
New Calling constructors to create objects Returns a newly created object, within the constructor, this is pointed to the newly created object.
Delete Variable, property deletion Delete an attribute (a variable can be viewed as a property of a global object or execution Environment).
void return to undefined.
In Judging attributes An attribute on an object property or a chain of prototypes.
instanceof Prototype judgment Compares whether an object in the same context is a prototype of another object.
Other operators ?: Conditional operator syntax; var value = exp? Trueexp:falseexp. equivalent to Var value; if (exp) {value = Trueexp;} Else{value = Falseexp;}
, Comma operator Mainly used to declare multiple variables, this is also a lot of JS Library popular practice. For example: Var num1=1,num2=2,num3=3;
() Grouping operators

Main uses:

1, the combination of the comma operator for assigning values. For example: var num = (5,1,4,8,0); the last value for num is 0.

2. Convert to an expression. For example, eval (' (' +jsstr+ ') ');
function fn () {
}//function declaration, cannot directly call
(function fn () {
}) ()///use () to enclose the function, you can directly call the
3, for calling functions. such as FN ();

typeof Type operator

Returns a String value: undefined type-> ' undefined ', null type-> ' object ', Boolean type-> ' Boolean ', Number type-> ' number ', string- > ' string ', instance of built-in function object-> ' function ', other object type-> ' object '. (some browsers implement slightly different)

Description of the points:

1, the classification here is not very strict, such as bitwise NON (~), logic is not (!), delete, void, typeof, can be regarded as a unary operator, and self-increase (+ +) in a lot of data are also classified as arithmetic operators. I am in the collation of the main reference to the original book classification, but also take into account the nature.

2, plus (+) The use of more flexible, need to pay attention to, especially for the calculation, ignoring the string, it will be easy to make mistakes.

3, typeof is generally used to judge simple data types, if the object type, because most of the return is object, not much practical use, and instanceof judgment also need to meet the conditions of the same context, otherwise there will be errors, The judgment of the object class explains the other, more conservative approach, when you're talking about the object later.

4, first look at the following code:

Copy Code code as follows:

var numval = 10.00,
Strval = ' 10 ',
Strobj = new String (' 10 ');
Console.info (Numval = = strval);//true
Console.info (typeof (Strval+strobj));//string

The first output is true, is it not surprising you? Here, because of the implicit type conversion of the = = comparison character, the number type is converted to a string type, and then 10.00 of the type numbers is parsed into integer 10 because there is no value after the decimal point that is not 0, which is equal when compared. The second output is string, which is actually relatively easy to understand, Strval is a string, Strobj is a string object, adding both adds an object to a string, so the end result is also a string type.
5, about the symbol, repeat a few popular usage (here does not involve the use of regular expressions):
(1) Convert to number type using a unary plus sign (+).
(2) Use double logic non (!! is converted to a Boolean type.
(3) Use logic and (&&) to detect if an object exists and follow up.
(4) using logic or (| | To provide default values for function parameters.
(5) Use Grouping (()) to explicitly specify as an expression.
(6) Use curly braces ({}) to define object literals, JSON data formats, code blocks.
(7) Use brackets ([]) to define the array literal, JSON data format, access array, access name is a variable or special character properties.
6, on the bitwise operation, although the results are not very intuitive, but the operation of high efficiency, there are many interesting applications, such as the use of intermediate variables to directly exchange two values, to determine odd and even, MD5 encryption, and so on, interested friends can find relevant information on their own research.

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.