JavaScript advanced Path (ii)--variables and basic data types

Source: Internet
Author: User

Objective

The variable in JavaScript is loosely typed, which means that when a variable is declared it can save any type of value, or it is not like SQL to declare that a key value of int can only hold the integer value, stating that varchar can only save the string. The type of value saved by a variable can also be changed, which is completely valid in JavaScript, but is not recommended. Compared to the variable as a "box", "JavaScript programming precision" mentions that the variable should be understood as "tentacle", it does not save the value, but the fetch value. This is more noticeable when the variable holds the reference type value.

A variable in JavaScript may contain values for two different data types: The base type and the reference type . The base type refers to simple data segments, whereas reference types refer to objects that may contain multiple values. This article mainly introduces the basic data types and their characteristics.

The base types are:Null,Undefined, number,String,Boolean. Reference types mainly include:Object,Array,Date,RegExp,Function.

Next, we introduce five basic types. Citation type this dish hopes to communicate with you in the future blog post.

Statement

In JavaScript, the declaration variable through the VAR operator, the declared variable will become its scope of local variables, meaning that the global declaration of the variable is generally referred to as a global variable, in the function declaration of the variable is the function as the scope of the local variables, local variables will be destroyed after the function is completed , variables declared without the var operator default to global variables. A single var operator is required to declare multiple variables at once, and the code is more concise.

var name = ' Susan ',    = ' All ',    = ' female ';
typeof operator

Before introducing the primitive type values, the TypeOf operator is the first, and the TypeOf operator returns a string representation of the data type. It is used to detect the efficiency of the base data types, and the instanceof operator is commonly used when detecting reference types.

typeofUndefined//undefinedtypeof  -;// Numbertypeof false;//Booleantypeof NULL;//Objecttypeof 'ABC';//stringtypeofA1};//Object

The difference here is that typeof will return the string "Object" when it detects NULL, because NULL is used as a null object pointer in JavaScript, and this is also Douglas in the JavaScript language pristine. But it's all right to understand.

Undefined type

The undefined type has only one special value, which is undefiend. All uninitialized variables will hold the value.

var//undefined

One thing to note here is that undefined is different from undefined variables, and if you call an undefined (declared) variable in your code, the parser prompts you for the following information.

Meaning that this variable is not declared, the way to find it is by searching up the scope chain, and if there is no declaration that the variable is found in the global environment, throw an error, this part of the course will be discussed with you later.

Null type

The null type also contains only one value, which is null, and logically it is treated as a null object pointer, precisely because of this feature, if you define a variable when you are not sure what value is currently assigned, but you need to assign an object type value in the future, the correct way is to initialize the variable to null.

Here is a quote that returns True when NULL is compared to undefined = =, which, according to JavaScript advanced programming, undefined derives from null, so ECMA-262 specifies that both equality operations are true.

Boolean type

The Boolean, commonly known as Boolean, consists of only two values: True and False. Here is a Boolean () transformation function that can be used on any type of value to convert other type values to Boolean. The conversion rules are mainly as follows.

String type: Non-empty string-true, empty string ("")-false

Number type: Any non-0-true,0 and Nan-false

Object type: Any object-true,null-false

Undefined type: false

However, this transformation function is not used to convert data types, and automatic type conversions occur when an if statement is encountered. Automatic type conversion has its advantages and disadvantages, and it is no longer extended. It is important to understand the transformation rules through the Boolean transformation function for use in encoding.

Here's a very simple example: in an app you need to detect if a user ID is cached locally to determine if a login is required.

if (!localstorage[' MemberID ') {   // login action     }

Here, when there is no user ID locally, the Localstorage value is undefined, the converted value is false, the non-operation is true, and the logon operation is performed. And do not need to write localstorage[' MemberID '] = = = undefined and so on.

Number Type

The number type in JavaScript supports decimal, octal, and hexadecimal values. About floating-point values here are a few things to note, in JavaScript, 0.1 is the same as. 1, but this omission is not recommended. Since the memory required to save the float is twice times the integer type, JavaScript converts the unnecessary float type to integer at the appropriate time, such as 10.0 of the floating-point type automatically saved as 10 of the integer type. It is particularly important to note that floating-point operations are far less accurate than integer types, as shown in the following example:

Console.log (0.1 + 0.2);

As you can see, the operation does not get the desired result, so be aware of this in the actual operation, and this example also reflects that the highest precision of the floating-point type in JavaScript is the 17 decimal place displayed. A number that is too large or too small can be expressed by using scientific notation E, which is not to be mentioned.

Infinity

The value that JavaScript can hold is not infinite, and when it is greater than or less than a certain limit, it is automatically converted to a special value-Infinity, Infinity also includes both positive and negative. Detects whether a value is infinity can be passed through the isfinite() function.

NaN

There is also a very special value in the number type, which is Nan, which is a non-numeric value (not a number). The existence of this special value is to avoid the need to return a numeric value, because the operation problem does not return a numeric error, affecting the program to run. For example, a number divided by 0 will throw an error in other programming languages, and Nan will be returned in JavaScript.

Nan has two features: 1. Any operation involving Nan will return Nan,2.nan not equal to any value, including his own =.=, that is, the equality validation of Nan = = Nan will return false.

Detecting whether a value is Nan can be used with the IsNaN () function, which attempts to convert the received parameter to a numeric value, meaning that the string "10" can be converted to a value of 10, while the string "color" does not work. The conversion successfully returns false, and vice versa is true.

numeric conversions

Numeric conversions of number types can pass through three functions: Numbers(),parseint (),parsefloat (). Because the number () conversion function is a wonderful (complex and unreasonable) conversion rule, the main introduction here is parseint () and parsefloat ().

First, it is stated that the parseint () and parsefloat () functions are specifically used to convert strings into numbers. This can lead to confusion, which is clearly used to convert a numeric value, and why to receive a string. As a simple example, parseint () will automatically convert to a string representation of this value when it receives the 3.14 floating-point value-"3.14", which converts 3.14 to 3 logically, it is not true that it can actually take an integer value, but instead encounters a decimal point when parsing the string "3.14". .” A character that cannot be converted to a numeric value automatically omits what is behind it.

With this understanding, let's look at the specific conversion rules for these two functions:

The parseint () function ignores the preceding space when converting a string until it finds the first non-null character. Returns Nan if the first non-null character is not a numeric character or a minus sign. If the first character is a numeric character, it continues to parse the second until the entire string is parsed or a non-numeric character is encountered (as in the example above 3.14).

// NaN // 3 // 4 // NaN // 123

parseint () can also parse binary, octal, and hexadecimal values, since the ECMAScript version differs in the resolution of non-decimal numbers, it is best to pass in the second parameter as the cardinality.

//  the //  the // 188

Similar to the parseint () function, parsefloat () is also parsed from the first character until the end of the string or when an invalid floating-point number character is encountered. For example, the first decimal point is valid and the second one is invalid, so the subsequent characters are ignored. Unlike parseint (), it always ignores the beginning of 0 and does not have the ability to pass in the cardinality, that is, only decimal values can be parsed.

// 123 // NaN // 12.3 // 34.5 // 34.5
String type

There is no difference between using single and double quotes in JavaScript, just be aware that the start and end are consistent. There are also escape characters in JavaScript, which are basically consistent with other languages and are not described here. Any string can get its length through the length property.

var str = ' Hello world '// One

Here is a brief description of a feature, the string once created in the ECMAScript can not be changed, such as splicing a string, the first is to create a new string, the original string is combined after loading, and finally destroy the original two strings. So it's not a simple concatenation as it seems.

String conversions

There are two ways to convert a value to a string type: 1. toString () method, 2. String () transformation function. The difference between the two methods is that the null,undefined value does not have the ToString () method, and any type value can use the string () function.

var num = 123//"123"varfalse//"false "

In most cases, calling the ToString () method does not have to pass arguments. When you want to determine the different binary of the output value, you can pass in a cardinality.

var num = ten//"Ten"//"1010"//"a"//  "Ten"//"a"

You can use the string () method when you do not know whether the value to convert is null or undefined. The rule is: if the value has the ToString () method, the method is called, and if null or undefined returns its string representation .... Well, in short, using the string () transformation function is not wrong.

// "Ten" String (True//"true"string (null//"null"//" Undefined "
Thank you for your visit, I hope to be of some help.

JavaScript advanced Path (ii)--variables and basic data types

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.