JavaScript Advanced Programming (3rd Edition) Learning notes 3 JS Simple data Type _ basics

Source: Internet
Author: User
Tags integer division numeric value object object throw exception wrapper
ECMAScript is a dynamically typed language built on the basis of 5 simple data types (Undefined, Null, Boolean, Number, String), and a complex data type (Object). This article will review the simple data type, I will try to describe from the perspective of programming practice, the following code to run the environment for Firefox 14.0.1.

Simple data type

Simple data type Take value
Undefined Undefined (only one value)
Null Null (only one value)
Boolean True|false (only two values)
Number Numerical
String String

The first thing to note is that in ECMAScript, these 5 simple data types, where a Boolean, number, string have a built-in wrapper object with the same name, and the literal value (variable) of a simple data type is automatically packaged according to the situation, so that the method can be called directly. As for the specific methods that can be invoked, elaborate on the built-in objects when discussing them:

Copy Code code as follows:

Console.info (True.tostring ())//true, equivalent to using a Boolean () wrapper before calling
Console.info (Boolean (False). ToString ());//false, converts false to a Boolean value
Console.info (new Boolean (false). ToString ());//false, false using a Boolean () wrapper
Console.info (False.tostring ())//false, equivalent to using a Boolean () wrapper before calling
Console.info (' Test '. toString ());//test, equivalent to using string () wrapper before calling

try{
Console.info (Undefined.tostring ());//no corresponding wrapper type, throw exception
}catch (e) {
Console.info (e);//typeerror
}
try{
Console.info (Null.tostring ());//no corresponding wrapper type, throw exception
}catch (e) {
Console.info (e);//typeerror
}

var num = 4;
Console.info (Num.tostring ());//4, you can call a method directly on a simple numeric variable, which is equivalent to using the number () wrapper before calling the
Console.info (3.toString ());//syntaxerror, syntax errors cannot be caught with a try, which means you cannot call directly on numeric literals

Second, the most data conversions that are actually used:
(1) Convert to boolean:!! Value
(2) Convert to Number:+value
(3) Convert to string: ' +value
5 simple data types are specified below:
1, undefined type
Undefined data type has only one value: undefined.
(1) All uninitialized values default to undefined (there is no need to have a variable display initialized to undefined).
(2) In a function scope, there is no function parameter passed in to the actual argument as undefined.
(3) When the function does not return explicitly or returns, the return value is undefined.
(4) in ECMAScript, the specified null==undefined returns true, and Null===undefined returns false.
(5) undefined the corresponding Boolean value is False.
(6) When acting on Undefiend using typeof, the return string ' undefined ', which acts on a "variable" that has never been declared, returns ' undefined '.
(7) The undefined conversion value is Nan and the conversion string is ' undefined '.
Copy Code code as follows:

Console.info (undefined===undefined);//true
Console.info (typeof undefined);//undefined
Console.info (typeof nodefined);//undefined, undefined identifier, returns typeof with Undefined, which is also the only operator available for undefined identifiers
Console.info (!undefined);//true, here returns True, which is the basis for determining whether a variable is initialized in many conditional statements
Console.info (!!) undefined);//Any value, use double negation!! Converts it to the corresponding Boolean value, which indicates that the corresponding Boolean value of Undefiend is False
Console.info (undefined==null);//es, null and undefined equality test returns True
Console.info (undefined===null); but undefined and null, after all, are two data types, return False when using strict equality comparisons
Console.info (typeof undefined==undefined);//false,typeof undefined returns a string ' undefined ', so this output is false
Console.info (+undefined);//nan, when converting values to NaN
Console.info (' +undefined);//undefined, convert to string ' undefined '

2. Null type
A null type also has only one value: null.
(1) When using typeof for null values, returns the String ' object '.
(2) Null the corresponding Boolean value is False.
(3) If a variable is used to save an object, it is recommended to initialize to NULL.
(4) Null conversion value is 0, conversion string is ' null '.
Copy Code code as follows:

Console.info (null===null);//true
Console.info (typeof null);//object
Console.info (!null);//true
Console.info (!!) NULL);//false, indicating null the corresponding Boolean value is False
Console.info (undefined==null);//true
Console.info (undefined===null);//false
Console.info (+null);//0, convert to value 0
Console.info (' +null);//null, converting to string ' null '

3. Boolean type
The Boolean type has only two values: True and False.
(1) Although only two values, but the value of any one data type can be converted to its corresponding Boolean value, the main conversion mode of three kinds:
A, through the Transformation function Boolean () transformation
Note that when a Boolean () as a conversion function is converted to a Boolean value corresponding to it, an object is created when it is a constructor, and the Boolean value of any Non-null object is true, sometimes misleading, suggesting that you do not use a Boolean ( )。 There is a similar case for string (), number ().
B, through double negation!! operator conversion
C, through implicit conversions, such as in some conditional statements
(2) Boolean True and False, when using TypeOf, returns the string ' Boolean '.
(3) When converting to a numeric value, True and false are converted to 1 and 0, respectively, ' true ' and ' false ' when converted to a string.
Copy Code code as follows:

var value = ' Test ';
var empty = ';
Console.info (!!) value);//true
Console.info (!!) empty);//false
Console.info (Boolean (value));//true
Console.info (Boolean (empty));//false
Console.info (!!) Value = = Boolean (value));//true, which shows that the two conversion methods are equivalent
Console.info (!!) empty = = Boolean (empty));//true
Console.info (value);//boolean object, note that the new is used here to create an object
Console.info (new Boolean (empty));//boolean Object
if (value) {//implicit conversion to True
Console.info (value);//test
}
if (empty) {//implicitly cast to False, do not execute parentheses inside statement
Console.info (' empty ');
}
if (new Boolean (empty)) {//Create object First, then implicitly convert to True, execute the statement inside parentheses
Console.info (' empty ');//empty
}
Console.info (typeof true = = ' Boolean ');//true
Console.info (+true);//1, unary operator, converted to numeric 1
Console.info (+false);//0
Console.info (' +true);//true, overloaded + operator, converted to string ' true '
Console.info (' +false ');//false


The specific conversion rules are as follows:

Data type Value converted to True The value converted to false
Undefined - Undefined
Null - Null
Boolean True False
Number Any value other than 0 (including infinity) 0 and Nan
String Any non-empty string Empty string
Object Any object -

4, Number type

In the ECMAScript, there is no separate integer, floating-point type, only a number type, using the IEEE754 format to represent (this notation in the calculation of rounding error), where not to examine the bottom of the implementation, these things in school C language has been very headache, do not want to have a headache once. The following I put the most of the actual programming used to the most, which is generally enough, for those who do not want to be bothered by the details of too much edge, at any time can skip the later on the discussion of number.

(1) numeric conversion: The main is the following three conversion functions

    • Number () function: Similar to Boolean (), converts data to number type and uses the same as the unary plus operator (+), and it is recommended to use the + operator, which is relatively simple.
    • parseint () function: parse integers, which can be passed in data and into the system, such as parseint (' 070 ', 8) output 10 56.
    • Parsefloat () function: Resolve floating-point numbers, only accept one parameter, it should be noted that if the parsed data result is an integer, it will return the integer directly.

Note: When using number () and + conversions, true->1,false->0,undefined->nan,null->0, empty string->0, Non-empty string-> by numeric resolution.

Copy Code code as follows:

var trueval = true;
var falseval = false;
var undef = undefined;
var nullval = null;
var intval = ' 1 ';
var floatval = ' 1.0 ';
var strval = ' Test ';
var empty = ';
Console.info (number (trueval));//1
Console.info (number (falseval));//0
Console.info (number (undef));//nan
Console.info (number (nullval));//0
Console.info (number (intval));//1
Console.info (number (floatval));//1
Console.info (number (strval));//nan
Console.info (number (empty));//0

Console.info (+trueval);//1
Console.info (+falseval);//0
Console.info (+undef);//nan
Console.info (+nullval);//0
Console.info (+intval);//1
Console.info (+floatval);//1
Console.info (+strval);//nan
Console.info (+empty);//0

Console.info (parseint (Trueval));//nan
Console.info (parseint (Falseval));//nan
Console.info (parseint (undef));//nan
Console.info (parseint (Nullval));//nan
Console.info (parseint (intval));//1
Console.info (parseint (floatval));//1
Console.info (parseint (Strval));//nan
Console.info (parseint (empty));//nan

Console.info (parsefloat (Trueval));//nan
Console.info (parsefloat (Falseval));//nan
Console.info (parsefloat (undef));//nan
Console.info (parsefloat (Nullval));//nan
Console.info (parsefloat (intval));//1
Console.info (parsefloat (floatval));//1
Console.info (parsefloat (Strval));//nan
Console.info (parsefloat (empty));//nan

Description: The behavior of these conversion functions may vary depending on the implementation of the browser, it is recommended that in the actual programming of the question of the first to write their own test. In the JavaScript Advanced Program (3rd edition), this section describes a lot of different things that I actually run, like the original book says parseint () can only parse strings, but the following code works:
Copy Code code as follows:

var object = {
Value:1,
Tostring:function () {
return this.value;
}
};
Console.info (parseint (object));//1

(2) integer and floating point number: By the C language edification of people, must be stubborn to distinguish between the integer and floating-point number bar! In the ECMAScript, they are not as different as expected, simple point, contains a decimal point and after the decimal point is at least one is not 0 of the number is a float, otherwise is an integer, such as 1.01 is a floating-point number, 1., 1.00 because there is no 0 after the decimal point, the engine resolves to integer 1. You might imagine that two integer division results will also be rounded, such as 3/2 = 1, but in ECMAScript, don't worry about it, you've restored its math properties, you'll find 3/2 = 1.5, which is also mentioned in the operator-related section.

(3) System: Also called carry system, is actually carry (low to high) method, each of the system has a base, when the low number reached this base, to the high level into 1. In daily life, the most used natural is 10 of the system, for example, the 10-point carry for 1 yuan, in the time metric, there are 24 (24 hours for 1 days), 60 in (60 seconds for 1), in ancient times, there is also the use of 16 into the system (think about Dora Bar). But in the processing of the computer, because the current only pass and impassability two states, so can only deal with 2 of data, but this is not good for natural people to understand, and then use 8, 16 into the production of 10 and 2 into the middle of the transition.

In ES3, you can use 8, 10, and 16, but in ES5, 8 is already disabled.

8: Starting with 1-digit 0, followed by the 8-digit sequence (0~7), if the number exceeds 7, the leading 0 is ignored as 10, such as 08, which resolves to 10-digit 8.

16: Begins with a 1-digit number 0 and 1 letter x followed by a 16-digit sequence (0-9a-fa-f).

10: You can write all digits one by one directly, or you can use the scientific notation (do not understand?). Look for a middle school math textbook to show it.

(3) Special value: In ECMAScript, there are 2 special values Nan and infinity need to note that the former represents not a numeric value (not a number), the latter represents a value that is not in the range, and can be used to indicate direction. For these two special values, here is not to examine the specific operation rules (if you are interested, you can test yourself, I will give some examples below), only to do the following two points:

A, you cannot use Val==nan to determine whether a variable is Nan, but to use the global isNaN () function, which accepts a parameter that returns True when the argument can be converted to a numeric value, or false.

B, try not to use val==infinity to judge whether it is out of range, and use the global Isfinite () function, which takes a parameter that returns True when the value of the parameter is in the range of representations, otherwise it returns false. The range of representations here is from Number.min_value to Number.MAX_VALUE, plus, in number, with attributes Number.negative_infinity and number.positive_ INFINITY, the values are INFINITY and-infinity respectively.
Copy Code code as follows:

Console.info (0/0); NaN
Console.info (Nan==nan);//false
Console.info (nan+1);//nan
Console.info (Nan/nan);//nan

var notnumber = NaN;
Console.info (Notnumber==nan);//false
Console.info (isNaN (Notnumber));//true
Console.info (1/0); Infinity
Console.info ( -1/0); -infinity
Console.info (1/infinity);//0
Console.info (infinity/infinity);//nan
Console.info (infinity==infinity); True
var inf = Infinity;
Console.info (inf==infinity);//true
Console.info (!isfinite (INF));//true
Console.info (!isfinite (NaN));//true
Console.info (isNaN (Infinity));//false

Note: on page 29th of JavaScript Advanced Programming (3rd edition), any number divided by 0 will return Nan, which is not actually the case.

5, String type

Unlike the General Class C language, there is no character type in ECMAScript, and string type string is used as a simple type, and its literal usage is enclosed in quotes (single quotes ' or double quotes ').

(1) for a string-type operation, the plus sign "+" is overloaded, and any number added to the string is first converted to a string by using string (), and then the two strings are merged.

(2) Use String () to convert,undefined-> ' undefined ',null-> ' null ',true-> ' true ',false-> ' false ', numeric type number-> The object object-> calls ToString by numeric values that are visible in character conversions.
Copy Code code as follows:

Console.info (' +1+1);//11, not 2.
Console.info (' +true ');//true
Console.info (' +undefined ');//undefined
Console.info (' +null ');//null

(3) The string is escaped with a backslash "\", and some common escape characters are:

Literal amount Meaning Literal amount Meaning
\ n Line Wrap \\ Back slash
\ t Tab \' Single quotation mark
\b Space \" Double quotes
\ r Enter \xnn A character expressed as a hexadecimal code NN
\f Paper Feed \unnnn A Unicode character represented in hexadecimal code nnnn

Well, for simple data types, just sort this out.

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.