2. Data type

Source: Internet
Author: User
Tags type null

Learning Essentials:
1.typeof operator
2.Undefined type
3.Null type
4.Boolean type
5.Number type
6.String type
7.Object type


There are 5 simple data types in ECMAScript: Undefined, Null, Boolean, number, and string.
There is also a complex type--object. ECMAScript does not support any mechanism for creating a custom, all values are
For one of the above 6 data types.


One, typeof operator

The typeof operator is the data type used to detect variables. Using the typeof operator for a value or variable returns the following Word
Character string.


String description
Undefined not defined
Boolean Boolean value
String strings
Number value
object or null
function functions


var box;
Alert (typeof box);
box is the undefined type, the value is undefined, and the string returned by the type is undefined

var box = true;
Alert (typeof box);
Box is a Boolean, the value is true, and the string returned by the type is a Boolean

var box = ' Journey ';
Alert (typeof box);
box is a string type, the value is ' journey ', the type returns the string

var box = 100;
Alert (typeof box);
box is the number type, the value is 100, the type returns the string

An empty object, which means that the object was created, and there was nothing inside.
Empty object, which means that there is no such object, which is a null
var box = {};
Alert (typeof box);
box is the object type, the value is [Object Object], and the string returned by the type is Object

var box=new Object ();
Alert (typeof box);
box is the object type, the value is [Object Object], and the string returned by the type is Object

var box=null;
Alert (typeof box);
box is a null type, the value is null, and the string returned by the type is Object
Note: null is one of the objects but is of type null

function box () {
}
Alert (typeof box);
Box is a function, the value is function box () {}, and the string returned by the type is function


Alert (typeof ' Journey ');

The typeof operator can manipulate variables or manipulate literal values. Although this can also be used: typeof (Box),
However, TypeOf is an operator rather than a built-in function. PS: The function is an object in ECMAScript, not a data
Type, so it is necessary to use TypeOf to differentiate function and object


Ii. Types of undefined

The undefined type has only one value, that is, a special undefined. Variables are declared using VAR, but they are not initially
Initialization is that the value of this variable is undefined.

var box;
alert (box);

var box=undefined;
alert (box);
It's not necessary to write like this.

PS: We do not need to show a variable assignment to undefined, because a variable with no assignment is implicitly (
Automatic) assignment is undefined, while the primary mother of undefined is for comparison, ECMAScript
This value was not referenced before version 3 and was introduced in order to formally differentiate between empty objects and uninitialized variables.

Uninitialized variables are not the same as variables that do not exist at all (undeclared variables).

var box;
alert (age);
Age isn't defined
You must declare a variable in the future to be initialized to avoid this problem

PS: If typeof box,typeof age returns the undefined. Logically think that their values are one
is undefined, one is an error, and their types are all undefined. So, when we're defining variables,
As far as possible, do not only declare, do not assign value.


Three, NULL type

A null type is a type that has only one value, that is, a special value of NULL. It represents an empty object reference (pointer),
While the typeof operator detects NULL, it returns an object.

var box = null;
Alert (typeof box);

If the defined variable is intended to be used to hold the object in the future, it is better to initialize the variable to null. This way, when the inspection
Check the null value to see if the variable has been assigned an object reference.

var box = null;
if (box!=null) {
Not equal to NULL description is not an empty object
Alert (' box object already exists! ‘);
}

var box = null;
This means that you have not yet created the object, but first declared the object reference and must initialize the result
You haven't had time to create an object, declare a variable of an object over there, and initialize it to NULL by default
For example:
var box = null;
Initialize first
box = {
1:1
};
Re-assign Value
alert (box);

The same string can also be written
var box = ';
Create a string variable, and at first do not know what string to initialize, so give him an empty string initially
Of

Numerical
var box = 0;
Numeric initialization, typically with 0

var box = false;
Boolean initialization, usually with true or false;


One of the reasons for this is that undefined is derived from null, so ECMAScript-262 prescribes equality for them
The test returns TRUE.

alert (undefined==null);

Because the comparison of undefined and null two values is equal, uninitialized variables and null-assigned variables
will be equal. At this point, the type of the typeof variable can be used for comparison. However, it is advisable to develop code that does not
To forget to initialize the variable.

var box;
var car = null;
Alert (typeof box = = typeof car)


Four, Boolean type

The Boolean type has two values (literal): true and False. And true does not necessarily equal 1,false not necessarily equal to 0,
JavaScript is case-sensitive, true and false, or none of the other values are of type Boolean.

var box = true;
Alert (typeof box);

Although the Boolean literal value is only true and false two, all types of values in the ECMAScript have
A value equivalent to the two Boolean values. To convert a value to its corresponding Boolean value, you can use the transform function
Boolean ().

var hello = ' Hello world! ';
var Hello2 = Boolean (hello);
Alert (typeof hello);

Above is a display conversion, which is a mandatory conversion. In practical applications, there is also an implicit conversion. For example, in the If bar
The conditional judgment inside a statement, there is an implicit conversion.

var hello = ' Hello world! ';
if (hello) {
Alert (' If the condition is true, execute my this one! ‘);
}else{
Alert (' If the condition is false, execute me! ‘);
}

var box = ' Journey ';
The IF (box) {///conditional statement must be a Boolean, true, or false
Alert (' true ');
}else{
Alert (' false ');
}


The following are other types that are converted to a Boolean type rule

A value that converts the value of the data type to true to False
Booleantruefalse
String Null string any non-empty string
Number any non-0 numeric value (including infinity) 0 and Nan
Object NULL for any objects
undefinedundefined


V. Type of number

The number type consists of two values: integers and floating-point numbers. To support various numeric types, the ECMAScript-262
The different numeric literal formats are justified.

The most basic numeric literal is a decimal integer.
var box = 100;//Decimal integer

octal numeric literal, (Radix 8), leading must be 0, octal sequence (0~7).
var box = 070;//octal, 56
var box = 079;//Invalid octal, automatically resolved to 79
var box = 08;//Invalid octal, automatically resolved to 8

Hex literal the front two bits must be 0x, followed by (0~9 and A~f).
var box = 0xa;//16 Binary, 10
var box = 0x1f;//16 Binary, 31

Floating-point type, which must contain a decimal point, and must have at least one digit after the decimal.
var box = 3.8;
var box = 0.8;
var box =. 8;//is valid, but not recommended

Because saving floating-point values requires twice times more memory space than integer values, ECMAScript automatically
A floating-point value converted to an integral type goes to an integral type.
var box = 8.;/ /No value after decimal point, converted to 8
var box = 12.0;//After the decimal point is 0, converted to 12

For those values that are too large or too small, they can be represented by scientific and technical law (e notation). Use e to indicate the value of the
The exponential power of the preceding 10.
var box = 4.12e9;//is 4120000000 4.12*10^9
var box = 0.00000000412//is 4.12e-9 4.12*10^-9

Although the highest precision of a floating-point value is 17 decimal, it may be imprecise in arithmetic operations. Due to this factor, doing
Be sure to take this into consideration when judging (for example, using integer judgments).
alert (0.1+0.2);//0.30000000000000004

The range of floating-point values is between: Number.min_value~number.max_value.
alert (number.min_value);//Minimum value
alert (number.max_value);//Maximum Value

If the maximum or minimum value of a floating-point value range is exceeded, then the infinity (positive infinity) appears first, or
-infinity (negative infinity).
var box = 100e100; Out of range, Infinity
var box = -100e100;//out of range,-infinity

may also be obtained through number.positive_infinity and number.negative_infinity infinity,
(positive infinity) and the value of-infinity (negative infinity).
alert (number.positive_infinity);//infinity (positive infinity)
alert (number.negative_infinity);//-infinity (negative infinity)

To determine whether a value exceeds the specified range, you can use the Isfinite () function. If not exceeded, the return
Returns true, exceeding the return false.
var box = 100e1000;
Alert (isfinite (box));//The return value is TRUE or False

NaN, or non-numeric (not a number) is a special value that is used to denote a
The operand of the value does not return a numeric value (so that no error is thrown). For example, in other languages, any numeric value
Dividing by 0 will result in an error and terminate the execution of the program. In ECMAScript, however, a special value is returned, so no shadow
The execution of the program.
var box = 0/0;//nan
var box = 12/0;//infinity
var box = 12/0 * 0;//nan

The Nan value can be obtained by Number.NaN, and any result of operation with Nan is Nan,nan and not
Equal (Nan is not equal to any value).
alert (Number.NaN);//nan
alert (nan+1);//nan
alert (Nan==nan);//false

ECMAScript provides a isNaN () function to determine whether the value is Nan. The IsNaN () function receives
After a value is attempted, the value is converted to a number.
Alert (IsNaN (NaN));//true
alert (IsNaN);//false, 25 is a numeric value
Alert (IsNaN ('));//false, ' 25 ' is a string value that can be converted to a numeric value
Alert (IsNaN (' journey '));//true, ' journey ' cannot be converted to a numeric value
Alert (IsNaN (true));//false,true can be converted to 1

The IsNaN () function also applies to objects. In the process of calling the isNaN () function, the valueof () method is called first, and then the
Whether the return value can be converted to a value. If not, the ToString () method is called based on this return value, and the test
The return value.
var box = {
Tostring:function () {
Return ' 123 ';//can be changed to return ' journey ' to see the effect
}
};
Alert (IsNaN (box));//false


There are 3 functions that can convert non-numeric values to numeric values: Number (), parseint (), and parsefloat (). Number ()
function when a transform function can be used for any data type, while the other two are specifically used to convert a string into a numeric value.
Alert (number (TRUE)), true and False for the//1,boolean type are converted to 1 and 0, respectively
Alert (number (25));//25, numeric type returns directly
Alert (number (null));//0, null object returned 0
Alert (number (undefined));//nan,undefined return NaN

In the case of strings, the following rules should be followed:

1. Strings that contain only numeric values are converted directly to decimal values, which are automatically removed if they contain leading 0.
Alert (number (' 456 '));//456
Alert (number (' 070 '));//70

2. Strings that contain only floating-point values are directly converted to floating-point values, which are automatically removed if they contain leading and trailing 0.
Alert (number (' 08.90 '));//8.9

3. If the string is empty, turn directly to 0.
Alert (Number (")");//0

4. If it is not the above three string types, the Nan is returned.
Alert (' journey100 ');//nan

5. If the object is a time, first call the valueof () method and then determine if the return value can be converted to a number. If the conversion
The result is Nan, which is called by the ToString () method based on this return value, and then the return value is tested.
var box = {
Tostring:function () {
Return ' 123 ';//can be changed to return ' journey ' to see the effect
}
};
Alert (number (box));//123


Because the number () function is complex and unreasonable when converting strings, it is more commonly used when working with integers.
parseint ().
Alert (parseint (' 456journey '));//456, returns the integral part of the
Alert (parseint (' Journey456journey '));//nan, if the first is not a value, return NaN
Alert (parseint (' 12journey56journey '));//12, starting from the first value to the end of the last continuous value
Alert (parseint (' 56.12 '));//56, the decimal point is not a value, it is removed
Alert (parseint ("));//nan, Empty returns NaN

parseint () can recognize octal and hexadecimal in addition to the ability to recognize decimal values.
Alert (parseint (' 0xA '));//10, Hex
Alert (parseint (' 070 '));//56, octal
Alert (parseint (' 0xAjourney '));//100, Hex, Journey is automatically filtered out

The ECMAScript provides a second parameter for parseint () to resolve various conversions of the binary.
Alert (parseint (' 0xAF '));//175, Hex
Alert (parseint (' AF ', ' 16 '));//175, the second parameter specifies hex, which can be removed with a 0x preamble
Alert (parseint (' AF '));//nan, of course.
Alert (parseint (' 101010101 ', 2));//314, binary conversion
Alert (parseint (' 70 ', 8))//56, octal conversion

Parsefloat () is used for floating-point numeric conversions, and, like parseint (), resolves from the first bit to a non-floating-point numeric position.
Alert (parsefloat (' 123Lee '));//123, remove the unrecognized part
Alert (parsefloat (' 0xA '));//0, don't know hex
Alert (parsefloat (' 123.4.5 '));//123.4, only one decimal point
Alert (parsefloat (' 01234.400 '));//123.4, remove the front and rear guide
Alert (parsefloat (' 1.234e7 '));//12340000, turn the scientific notation into a normal value


Vi. type of string

The string type is used to represent a sequence of characters consisting of 0 or more 16-bit Unicode characters, that is, a string. String can be
denoted by double quotation marks (") or single quotation marks (').

var box = ' Journey ';
var box = "Journey";

PS: In some other languages (PHP), single and double quotation marks represent different ways of parsing strings, while ECMAScript
, the two representations do not differ in any way. But keep in mind that there must be a pair of occurrences that cannot be interspersed with, otherwise it will
Error.

var box = ' journey ';//error. Quotation marks must appear in pairs

The string type contains some special character literals, also called escape sequences
literal meaning
\ nthe line break
\ t watchmaking
\b Spaces
\ r Enter
\f in the system
\ \ Slash
\ ' Single quotation mark
\ "Double quotation marks
\xnn a character (0~f) example in hexadecimal code nn: \x41
\UNNN the hexadecimal code nnn represents a Unicode character (0~f) Example: \U03A3


The strings in the ECMAScript are immutable, that is, once the strings are created, their values cannot be changed. To
To change the string stored in the variable, first destroy the original string and then fill it with another string containing the new value.
The variable is charged.
var box= ' Mr ';
box=box+ ' journey ';

The ToString () method converts a value to a string.
var box=11;
var box=ture;
Alert (typeof box.tostring ());

The ToString () method generally does not need to pass arguments, but it can be passed into a string when the value is converted to a literal.
var box = 10;
Alert (box.tostring ());//10, default output
Alert (box.tostring (2));//1010, binary output
Alert (box.tostring (8));//12, octal output
Alert (box.tostring (10));//10, decimal output
alert (box.tostring);//a, hex output

If you do not know if the variable is null or undefined before transformation, we can also use the transformation function
String (), which can convert any type of value to a string.
var box = null;
Alert (String (box));//null,string type

PS: If the value has the ToString () method, the method is called and the corresponding result is returned; if null or undefined
, either "null" or "undefined" is returned.

Vii. type of Object
How to create a var box={};//object literal
Alert (typeof box);

The object in ECMAScript is actually a set of data and functions. Object can be executed by executing the new operator followed by the
Creates the name of the object type to create.
Var box=new object ();//Create an object from new

object is constructed, and if you do not need to pass arguments when initializing an object, you can not write parentheses, but this way does not push
Kanzian
var box=new Object;

Object () can be arbitrarily passed, you can pass the value, String, Boolean value and so on. Furthermore, it is possible to calculate accordingly.
var box=new Object (2);//object type, value 2
var age=box+2;//can be calculated with normal variables
alert (age);//output, transformation to number type

Now that you can use new object () to represent an object, we can also use this new operator to create its
Object of his type.
var box = new Number (5),//new String (' Journey '), new Boolean (True)
Alert (typeof box);//object type

PS: Object oriented is the focus of JavaScript course, here is a brief introduction. You will learn more later.

2. Data type

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.