Basic JavaScript concepts

Source: Internet
Author: User
Tags string methods
Document directory
  • Undefined
  • Boolean
  • Number
  • String
  • Object

The core of any language will describe the most basic working principle of this language, the description usually involves the syntax, operators, data types, built-in functions of the language, and other basic concepts used to build complex solutions.

Syntax

JavaScript draws on a lot of C and C languages. developers who are familiar with these syntaxes are very familiar with JavaScript. Here I will not explain them one by one, but will become familiar with JavaScript later, however, there are several points that need to be emphasized.

1. JavaScript is case sensitive, variable names, method names, and operators are all differentiated. I believe most developers are familiar with this, and many mainstream languages are familiar with this.

2. identifier. The identifier refers to the name of a variable, method, attribute, or method parameter. The identifier can be one or more characters in combination according to the following format:

A. the first character must be a letter, underscore (_), or $ (this $ must be noted that, unlike many languages, it can appear first );

B. Other characters can be the preceding characters or numbers.

3. By convention, JavaScript identifiers use the camper name method. The first letter is in lowercase, and the first letter of other meaningful words is in uppercase. Of course, no errors will occur if this name is not used.

4. the annotation style of JavaScript is the same as that of C. It can be divided into single-line and block-level annotations. A single-line annotation starts with two forward slashes, followed by a comment. A multi-line annotation starts with/* and ends, add comments in the middle

5. The JavaScript statement ends with a semicolon (;). If the semicolon is omitted, a parser ends with a definite end (it is not recommended to omit the semicolon)

Keywords and reserved words

Everyone on Earth knows that the keywords and reserved words are listed here for reference.

 

  
Keywords
Break Else New Var
Case Finally Return Void
Catch For Switch While
Default If Throw  
Delete In Try  
Do Instanceof Typeof  
 
Reserved Words
Abstract Enum Int Short
Boolean Export Interface Static
Byte Extends Long Super
Char Final Native Synchronized
Class Float Package Throws
Const Goto Private Transient
Debugger Implements Protected Volatile
Double Import Public  

Keyword-based identifiers in the code will report "Identifier Expected" (missing identifiers) in most browsers. If this error is correct, you can check whether the keyword is used as the identifier.

Variable

1. javaScript variables are still very interesting and used to use C or Java. Suddenly, JavaScript variables are loose, that is, weak types, data of any type can be saved. Each variable is just a placeholder for storing values. When a variable is defined, no type is specified. The var operator is followed by the variable name.

Var a; // only defines a variable and can store any value. undefined is not initialized.

Var B = 3; // initialize directly after Definition

Var c = "hello"; // (single quotation marks, double quotation marks are the same, just match)

2. variables defined using the var operator are local variables in the scope of the variable. They are valid in the scope. If var is used to define variables in the method, the variable is destroyed after the method ends.

Function test (){

Var message = "Hello there! "

}

Test (); // create a variable and assign a value when calling the method, and destroy the variable after execution.

Alert (message); // undefined

3. if you do not write the ar operator when defining a variable, the variable is defined as a global variable. After initialization, the variable can be used anywhere. However, it is not recommended to define global variables and is not easy to maintain, if a few developers develop at the same time, everyone will define global variables. When the naming conflict arises, it will be messy.

  

Function test (){

Message = "Hello there! "

}

Test (); // create a variable and assign a value when calling the method, and destroy the variable after execution.

Alert (message); // Hello there!

Data Type

There are also loose types. JavaScript has five simple data types, or basic data types, including Udefined, Null, Boolean, Number, and String, and a complex data type Object, an object is essentially composed of Oil-disordered key-value pairs. JavaScript does not support custom types, so all values in JavaScript are one of the preceding six types.

1. typeof ...)

If you want to know the type of a variable, you have to rely on the typeof operator. It is worth noting that typeof is an operator, not a method (so people's o is lowercase, this is to say, when detecting a variable type, you can use typeof XXX. You do not need to enclose the variables, even though many people include them, although it is correct, it is not necessary, but it seems to increase readability and tangle ..., another point is to use typeof to detect whether a function returns a function instead of an object. Although the function is also an object, it is special. typeof null also returns the object instead of null, this will be explained later.

Var message = "I'm a string ";

Alert (typeof mesage); // string

Alert (typeof (message); // string

Alert (typeof 34); // number

Undefined

The Undefined type has only one undefined value (case-sensitive, do not use quotation marks, but are not strings). As mentioned earlier, variables are defined using var, but not initialized, the default value of a variable is undefined. Generally, you do not need to explicitly define a variable as undefined. undefined is mainly used for comparison to distinguish between null object pointers and uninitialized variables.

Var message;

Alert (message = undefined); // true

However, the variables that contain the undefined value and the Defined variables are different.

Var message;

Alert (message); // "undefined" has quotation marks because alert calls the toString method, rather than undefined itself has quotation marks.

Alert (XXX); // error generated. It can be seen that undefined and uninitialized are different.

It's time to get stuck. It's easy to understand that undefined is returned for the uninitialized variable typeof operator. However, if you execute the typeof operator on undeclared variables, undefined is returned, therefore, you cannot use typeof to check whether a variable is defined or not. Likewise, if you use the typeof operator to detect a variable, returning undefined does not indicate that the variable is not defined. Therefore, when we define variables, we try to initialize the variables explicitly (assign values after definition). In this way, we can use typeof to return undefined to know that the variables should be defined, unless the variable is explicitly initialized to undefined, no one will do this ....

Null

This variable is well-known and exclusive to all languages, but Null in JavaScript has its own particularity. First, like Undefined, there is only one null value. Again, the first letter of the variable type is capitalized, however, the first letter of the value is lowercase. null indicates a null object Pointer, which is exactly why the object is returned when typeof null is used.

Var message = null;

Alert (typeof message); // "object"

If the defined variable is ready to be used to store the object, it is better to initialize it to null. In this case, you can determine whether to save the object reference in the variable if the variable value is null.

 

Null is also a pitfall. In fact, undefined is derived from null. In JavaScript, the two return true when making equal judgments, although undefined and null should not be confused.

Alert (undefined = null); // true

The above green font indicates incorrect understanding. The undefined on the first floor corrected the text and gave a thorough explanation. To prevent the readers from reading the text, I will copy it here:

The noble undefined and null are completely different.
= Not completely equal in javascript, but "equal after conversion type"

For example, 0 = '0'
Returns true.
This does not indicate that 0 and '0' have any relationship.

In fact, there are ===for comparison.
Null === undefined
Returns false.

In fact, except for some special cases (generally not a good case), ==is basically not used, and === is used for comparison. This is what we usually say is equal.

Boolean

The Boolean type has two values: true and false. In JavaScript, the values 0 and 1 are irrelevant. That is the Number type, but there are certain conversion rules, you can use Boolean () to convert a value to a corresponding Boolean value ()

Var message = "Hello ";

Var messageBool = Boolean (message );

It is quite useful to look at the conversion rules. If a crop is judged, the entire logic may be incorrect.

1. For non-null strings, convert to true, "" (empty string) to false

2. convert any non-zero number, including infinity to true, negative number, and NaN to false.

3. convert any object to true, convert null to false, and convert undefined to false.

Number integer

The Number type is often used, and there are many items in it. The basic value independent variable format is a decimal integer, which can be directly input.

Var a = 45; // integer

In addition to a decimal integer, it can also be expressed by octal or hexadecimal literal values. However, to distinguish between octal values, the first value of the octal value must be 0 and then the octal value (o ~ 7), the value exceeds the range. For example, if a value of 09 is written, the first 0 will be ignored. If it is processed in decimal format, the first two digits in hexadecimal format will be 0x, followed by a hexadecimal number (0 ~ 9, ~ F). The letters are case-insensitive. Indicates that it is in decimal format.

Floating point value

Floating Point number is the number of digits after the decimal point. Because the memory space required to save the floating point number is twice that of the certificate, JavaScript will convert the floating point number to an integer at the wrong time, if there is no number after the decimal point, or the number itself is an integer (3.0), JavaScript will automatically convert to an integer

Var num1 = 3.; // No number after the decimal point, resolved to 3

Var num2 = 4.0; // integer, resolved to 4

For extremely large or extremely small numbers, use scientific notation, and numbers + E (e) + integers. For example, 2.3E6 represents the 6 power of 2.3 multiplied by 10. Note that it is 10, not a natural constant. Basically, I have never handled such a big number problem in JavaScript.

Note that the highest precision of floating point numbers is 17 decimal places, and the precision is not so high during numerical calculation. You will be surprised to find that 0.1 + 0.2 is not equal to 0.3, but 0.30000000000000004

Value Range

Memory limit. floating point numbers have a range. The minimum JavaScript value is stored in Number. in MIN_VALUE, the maximum Number is stored in Number. MAX_VALUE is usually enough, but once the range is exceeded, the value is automatically converted to the Infinity value, and the affiliated value is converted to the Infinity value. These two infinite trees cannot participate in the calculation, the isFinite () method can be used to check whether the value is between the maximum and minimum.

Alert (isFinite (4564756); // true

Alert (isFinite (Number. MIN_VALUE + Number. MAX_VALUE); // false, these two cannot be involved in the operation

NaN

NaN is a non-numeric value. It is a strange name. It is easy to understand English. Not a Number. This value is used to indicate the case where an error occurred while returning the numeric value. For example, if any Number is divided by 0, NaN is returned, no error is reported. Nan has two features. First, any operation involving NaN will return NaN. Second, NaN is not equal to any value. Can Nan be different from himself.

Alert (NaN = NaN); // false

Can this be swollen? Do you know when the numeric value is calculated incorrectly? JavaScript provides an isNaN () d method, which accepts a parameter. If the parameter is of the numeric type, it is directly determined, if not, try to replace the package and try again.

Alert (isNaN (NaN); // true

Alert (isNaN (20); // false

Alert (isNaN ("10"); // false, which can be converted to a number 10

Alert (isNaN ("OK"); // true OK cannot be converted into a number

Alert (isNaN (true); // false, convert to number 1

Some strange thing is that the parameter can also be an object. In this case, the valueOf () method of the object is called first, and the value can be converted to a number. Otherwise, the toString () method is called and the return value is tested.

 

Numerical Conversion

There are three ways to convert a value to a non-numeric Number (), parseInt (), or parseFloat (). Number () can be converted to any data type, but the rule is strange. In many cases, it is not the result we want. If you are interested, you can check the Rules online, the latter two are converted to strings as numerical values, which is more practical.

When converting parseInt (), it is important to check whether the string conforms to the numeric mode. spaces are ignored. If the first non-null character is not a number or a negative number, NaN is returned. Otherwise, resolution continues, knowing that a non-numeric character is encountered, and then truncation, that is, "1234ABD" will be parsed to 1234, "23.45sdf" will be parsed to 23, it is worth noting that a string starting with 0 will be parsed into octal notation, and the string starting with 0x will be parsed into hexadecimal notation, so it is confusing to parse "070" and so on, in case of a problem, parseInt provides the second parameter, which can be passed into the hexadecimal number. The default value is 10.

Var num = parseInt ("0xAF", 16); // 175 returns the decimal value. It involves computation.

Var num2 = parseInt ("AF"); // NaN

Because not specifying the technology means that parseInt () determines how to parse the input string. To avoid parsing errors, it is best to write the second parameter

Var num1 = parseInt ("010"); // 8 parse by octal

Var num2 = parseInt ("010", 8) // 8 parse by octal

Var num3 = parseInt ("010", 10) // 10 is parsed in decimal format.

Var num3 = parseInt ("010", 2) // 2 parse by binary

ParseFloat () and parseInt () are similar, that is, we know the decimal point and e and will not repeat them here.

String

We all know that single double quotation marks are the same. Matching is the same. Some escape characters are the same as C. When calculating the length of a string, the escape character is calculated by one, and the index is the same, the length of yonglength attribute is obtained. It is not a method and there is no parentheses.

The string in JavaScript is immutable. Therefore, after the component string is initialized, the value is changed. In fact, the original string is destroyed and a new string is used as the variable, values, Boolean values, objects, and strings all have toString () methods. null and undefined are not supported. There are many string methods, which are common and flexible in usage, I will not list them here. Just give a link.

Http://www.dreamdu.com/javascript/object_string/. I think it's pretty good.

Object

This sentence is not clear and can only be simply mentioned. As more and more users use it in the future, they will gradually become familiar with it. JavaScript objects can be seen as a set of data and methods. It is easy to create objects.

Var o = new Object ();

Each instance of an Object has the following attributes and methods:

1. constructor stores the methods used to refer to the current object in a rough manner and explains the constructor.

2. hasOwnProperty is used to set up whether the specified property is in the current object, rather than in the instance prototype. The input parameter is the property name.

3. isPrototypeOf is used to check whether the input object is a prototype of another object.

4. propertyIsEnumrable is used to check whether the for in statement is sufficient for a given attribute.

5. toString.

6. valueOf is not much, as the name suggests.

In fact, I have the most feelings about String and Object, but I have the least. I will introduce these things in the future. If I have never learned JavaScript, it will make me confused, however, the following learning is clear. Here is a concept.

I will summarize the operator statements, methods, and functions next time.

From: http://www.cnblogs.com/dolphinX/archive/2012/03/18/2390040.html

Related Article

Contact Us

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

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

A Free Trial That Lets You Build Big!

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

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

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

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