5. Data type

Source: Internet
Author: User
Tags print object type null

Objective:
5 Primitive basic data types, also called value types: Undefined, Null, Boolean, number, and string.
Compound/reference Data type: Object, which is a collection of properties and methods, is essentially a set of unordered name-value pairs. There are also types such as array (), function (),
"Remember"
Value types: Numeric, Boolean, null, undefined. Reference type: object, array, function.
Difference
The basic data types are: ' Undefined,boolean,number,string,null. Basic types of access are accessed by value, that is, you can manipulate the actual values that are saved in the variable.
Reference data type: The storage of the reference type requires memory for the stack and heap to be completed together, the stack memory holds the variable identifier and a pointer to the object in the heap memory, or it is the address of the object in the heap memory.

Basic data type Memory storage mode

var name = ' Jozo '; var city = ' Guangzhou '; var age = 22;

How reference data types are stored

var person1 = {name: ' Jozo '}; var person2 = {name: ' Xiaom '}; var person3 = {name: ' Xiaoq '};

Packing class
To facilitate operation of the basic type values, ECMAScript provides wrapper classes for the 3 commonly used basic data types boolean,number,string, each of which has its own construction method. In fact, each time a primitive type value is read, the background creates an object of the corresponding basic wrapper type, enabling the invocation of some (constructed method-provided) methods to manipulate the data.
Number type wrapper class is number
String type wrapper class is string
The Boolean wrapper class is a Boolean

var str1= "Hello!" ; var s=str1.substring (2); alert (s); /* In the first line, I have given a string value to str1 in my usual habit. In the second line, I take a basic type of variable to access a method. The "interpret" access process is in a read mode, that is, to read the value of the string from memory, while accessing the string in read mode, the background will: 1, create an instance of String type: var str1=new string (' hello! '); 2. Call the specified method on the instance: Var s=str1.substring (2), 3, destroy this instance: Str1=null; Remember to destroy only the instance, not the previous primitive type value. So every time the method is called, it will be this way. */

Literal vs Create New Object assignment
Direct volume, also known as literal, is the representation (or creation) of an object in JS, which can be converted to a corresponding object by assigning the value of JS native object directly to the variable.
Instead, the object is created by new and then assigned a value. Is the standard way, but the basic data type for frequent use is too troublesome.
As you can see from this definition, this definition is actually declaring a variable of one type and assigning it at the same time. Therefore, the direct amount of the declared object can be used directly in the code without having to use the New keyword to create the object.

var str1= "Hello!" ; var str2=New String (' hell '); Console.log (typeof str1); // stringconsole.log (typeof str2); // Object /* string is a constructor, and string is a type of variable. Both of these are the same. It is also important to note that using new to invoke the constructor of the basic wrapper type, new creates all objects, so typeof is all object. So is not the same as the direct assignment is the data type is different * /

String
Format
String type is the most familiar, as for the use of single quotation marks, or double quotes, there is no difference in JS.

var firstname= ' Zakas ';

Object methods for string wrapper classes

length evaluates the Str.lengthindexof () index of the string in the position of the first occurrence of a specified character in the stringvarStr= "Hello"; Console.log (Str.indexof ("E"));//e The first occurrence of the position[Web browser] "1"match () looks for a specific character in a string and returns a secondary character if found. varStr= "Hello world!"Console.log (Str.match ("Hello")); Console.log (Str.match ("Hello")); [Web browser]"Hello"[Web browser]"NULL"the Replace () method replaces some characters in a string with some other charactersvarStr= "Hello world!"varNewstr=str.replace (/world/, "Girl") Console.log (NEWSTR); [Web browser]"Hello girl!"For more information, please refer to the manual http://www.w3school.com.cn/jsref/jsref_obj_string.asp

Number
There are two forms of representation of the type, the first being an integer and the second being a floating-point number.
The [positive] integer can be represented by decimal, octal, and hexadecimal literals.
[Floating point] is a decimal, and if only 0 after the decimal point, the decimal number is converted to an integer. Floating-point numbers occupy twice times as much memory space as integers.

var num=123; var num=1.23;

Number Object method

/* ToString Converts a number to a string */ var num=123var newnum=num.tostring (); Console.log (typeof num); // "Number" Console.log (typeof Newnum); // "string" /* please refer to the manual for other methods http://www.w3school.com.cn/jsref/jsref_obj_number.asp */

Boolean
That is, the Boolean type, which has two values: true false;

var x=true;

Boolean Object method
To create an object:

var x=New  Boolean (); /* If the parameter is not written, or 0,-0, NULL, "", false, undefined, or NaN, the object is set to False. Otherwise set to true (even if the value parameter is the string "false"). */

Method

// ToString Converts a Boolean value to a string var true ; Console.log (test+ "type:" +typeof test) // "True Type: boolean"Console.log (test.tostring () + "type:" +typeof test.tostring ())//" True type is: string "

undefeined
There are two things that can undefined,
When you declare a variable with VAR, but do not initialize it, the type of the variable is undefined, and its default initialization value is undefined.
For variables that are not declared and initialized and used directly, the type of the variable is also undefined, but there is no default initialization value.

var The type of message;console.log (' declared but uninitialized variable message ' is: ' +typeof  message ') Console.log (typeof age )/*[Web browser] The type of the variable message that has been declared but not initialized is: undefined "[web browser]" is not declared, Also uninitialized variable the type of age is: undefined "* /

The difference between the two cases
Because JS variables are declared with the keyword VAR, the specific type of the variable depends on the value of the variable that he is given, and for both of these cases, although they are inherently different, they are not initialized, so their type is undefined. However, the latter does not have an initialization value. So when

var message;console.log (Message) Console.log (age) /* [web browser] "undefined" [Web browser] "uncaught referenceerror:age is not defined" */

Null
JS 5 in the original data type inside, another type of only one value is NULL, it has only one private value null, that is, its literal. (for example, number literal can be any digit between 1-9)
Null is used to represent an object that does not already exist (this is briefly described when discussing the typeof operator).
Null is nothing, for example, space, empty string, 0, etc. are objects with actual values, and null of course there is a qualitative difference.

Console.log (typeofnull// Print Object/*   from a logical point of view, a null value represents an empty object pointer .    This is why the "object" is returned when using the TypeOf operator to detect null values.    JavaScript Advanced Programming (2nd edition) P22 said    in ECMA6, there was a proposal for historical vindication, the value of type NULL was corrected to NULL, but the proposal was rejected. The reason is that the history of legacy code too much, do not want to offend, Better keep will wrong when peacemaker * *

NaN "is not part of 5 basic data types, not commonly used"
Concept
is a non-numeric type, which is a shorthand for not a number. The value that belongs to the number type.
Note that it is not inside the original data type of JS 5.
The NaN property is a special value that represents a non-numeric value. This property is used to indicate that a value is not a number.

Console.log (typeof NaN)// will print number


Reference: http://www.w3school.com.cn/jsref/jsref_nan_number.asp
Executes the code, it should have returned a number, but the result is not, then it will return Nan, such as the bottom

 //  operator, cannot do arithmetic, or the result is not a number, returns Nan  Console.log (0/0); Console.log (Math.Round ()) //  When rounding fails, a Nan  console.log (math.sqrt ("Q")) //   when the square root fails, it returns nan  //  If you cannot cast, or the result is not a number, return nan  console.log ("Q")) //  When a strong-to-digital failure returns nan  //  when the specified string cannot be resolved, Or the result is not a number, it returns nan  console.log (parseint ("Q")) //  nan  console.log (parsefloat ("K") is returned when parsing a string and returning an integer failure //  
when parsing a string and returning a floating-point number failure

For some functions that return a valid number in general, you can also use this method to describe its error condition with Number.NaN, which has only one value: NaN.

// determine if the month is a regular and valid number var Month=30; if (Month < 1 | | Month >= Number.NaN; // Number.NaN value is Nan  // print nan

The property of the Number object nan--**pk**--the properties of the global object NaN
Reference: http://www.w3school.com.cn/jsref/jsref_nan.asp

In ECMAScript v1 and later versions, you can also replace Number.NaN with a predefined global attribute, NaN.
This property of the global object, Nan, is not commonly used, in fact, the property of the number object Nan is not commonly used!

Summarize:
1. Both the global object and the number object have an attribute Nan, which has only one value, Nan. But this attribute is rarely used by anyone
2. Most people use the global function isNaN () to determine whether a value is not a number.

/*IsNaN (x) determines whether a non-number, x is empty or non-number satisfies the condition. For example isNaN (5/0) is established. In short, a general sentence summary: As long as it is not a number, are trtue commonly used to detect the results of values, to determine whether they represent a valid number. */Console.log (IsNaN (1))//falseConsole.log (IsNaN (2-1))//falseConsole.log (IsNaN (5/0))//falseconsole.log (IsNaN ("5"))//false "Note"Console.log (IsNaN (0/0))//0 divided by 0 results for Nan,trueconsole.log (IsNaN ("5-2"))//trueConsole.log (IsNaN ("A"))//true//"Note": Why this is also OK, because "5" ==5, JS will automatically convert!!! So the type must be judged, and the TypeOf function is born. The following codeConsole.log ("5"-"3")//Results Print 2Console.log ("5-3")//Results Print 5-3

Last one:
Composite data type (reference data type)
Object
1. An object that is instantiated by this type is a set of data or functions or
2. There are two ways to instantiate an object (that is, to create an object), one through the new operator and one through the object literal notation. "JS does not have the concept of class, but the creation of objects also have a sense of class, in ES6 has introduced the class keyword classes"

//one is through object literal notationvarDsh={"Name": "Mr. Ding",//attribute notation 1Age: "30",//attribute notation 2Speakfunction() {alert ("Hello everyone, my name is" +dsh.name+ ", I" +dsh.age)}} Dsh.speak ()//one is through the new operatorfunctionpersion (name,age) { This. name=name;  This. age=Age ;  This. speak=function() {alert ("Hello everyone, my name is" +name+ ", I" +Age )}; WX=NewPersion ("Wang Xin", 20);//instantiating an objectWx.speak ()

3, the object type is the most basic composite data type, we can inherit more types on the basis of it.
As we know, array (), Date (), and interesting function () types are inherited from object. And these types are set by default by the programmer before the use of properties and methods, for the programmer to call.

4, and the above types have a general name for the reference type. Why is it a reference type?
Just use the idea of Java to understand---well, the beginning of this article is introduced, you are on the swipe up to see.

typeof

ECMAScript has 5 primitive types (primitive type), namely Undefined, Null, Boolean, number, and String
typeof is used to test the data type, it returns the top 5 primitive types and function

This article refers to:

http://www.jianshu.com/p/0d3034102220

1190000002789651

Http://www.jb51.net/article/63875.htm

5. 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.