JavaScript basic data types and value types and reference types _javascript tips

Source: Internet
Author: User
Tags garbage collection numeric value wrapper


Four basic data types in javascript: numeric values (integers and real numbers), string literals (characters or values enclosed by "" or "), Boolean (make True or false), and null values. The data in the basic type of JavaScript can be constants or variables. Because JavaScript takes the form of a weak type, a variable or constant of a data does not have to be declared first, but rather the type of its data when used or assigned. Of course, you can declare the type of the data first by automatically stating its data type when you assign a value.



Variables in JavaScript



A variable in JavaScript is just a placeholder, the preface has been said because of the loose type.



To define a variable:



var name;



The preceding code defines a variable named name that can be used to hold any value (such as an uninitialized variable, save a special value--undefined), or to initialize the value of a variable.


var name = "Jwy"; There is no difference between single and double quotes in JavaScript, but be aware of nesting
name=10 correctly;


The first name initialized to the string value "Jwy" and then to the numeric value of 100, which is not recommended, but it works in ECMAScript, and in many cases it does.



You can also define multiple variables with a single statement, and many JavaScript frameworks do this.


var name= "Jwy", author,age=29;


It's good programming practice to add a semicolon to each statement. However, when you have multiple variables, we recommend wrapping and indenting, which improves readability.



Simple data type



There are 5 simple data types in ECMAScript:undefined,null,boolea,number and String. There is also a complex data type-Object



typeof operator



Because the variable in JavaScript is loosely typed, it provides a way to detect the data type of the current variable, that is, the TypeOf keyword, in the 5 simple data types in the ECMAScript mentioned above (remember, these 5 are just data types, representing a data type, Just like the int,string type in C #, the TypeOf keyword returns the following value (shown as a string) to these 5 data types



"Undefined"----------if the value is not defined undefined



Boolean----------If this value is Boolean



' String '----------if this value is string strings



' Number '----------if this value is a numeric type #



"Object"----------if this value is an object or null



"Function"----------if this value is a function



But strictly speaking, a function is an object in ECMAScript, and each function is an instance of this class of functions, and since the function is an object, then it is a reference type, so a function is only a variable name, so it is often seen on many occasions, The function name is passed into the function as a parameter, and then called, which is similar to a delegate in C #, which will explain the function in detail later, after all, many things in JavaScript depend on the function to implement.



Undefined type



It says, 5 types are data types, so the data type is a value, and the value of the undefined is undefined, note that u is lowercase. If a variable is declared without initialization, the value of the current variable is undefined. However, it is generally recommended to initialize variables as much as possible, but in earlier versions of JavaScript there is no provision for undefined this value, so in some frameworks, in order to be compatible with older browsers, the window object is added with the undefined value, as follows:


window[' undefined '] = window[' undefined ']; 
Or


To put it simply is to assign a undefined to the undefined property of the Window object, and the older browser object does not undefined this property, so if the operation to undefined will cause an aberration, so in this way, But at first it would be a bit hard to understand that in an older browser it would be compatible with an old browser because it would return a undefined value because there was no window.undefined this object.



However, the variable containing the undefined value is not the same as the undefined variable, such as:


var name;
alert (name);//undefined
alert (age);//error: Age isn't defined


Variables that have not been declared can only perform one operation, none of which can be done by using the TypeOf operator to detect their data types.



A value that returns undefined, regardless of the declared uninitialized and typeof variable execution. Either way, you can't do the actual operation.



Null type



The value of a null type is NULL, it represents an empty object pointer, does not point to any object, if the value of a variable is null, the current variable is likely to be the object of garbage collection, using typeof to monitor null values will return "Object",


var person = null;
Alert (typeof person);//"Object"


Recommendation: If the variable is to be used to save the amount of the object, initialize to null, so that the variable can be detected to have saved a reference to an object.



Note: The undefined values are derived from null, so performing an equality test on them returns true, such as:


Alert (Null = = Undefind);//true


However, they are completely different, and no matter under what circumstances it is not necessary to set the value of a variable to undefined, but this rule does not apply to NULL.



Boolean type



This type has only two values: True and False. Although there are only two values, all types of values in JavaScript have values that are equivalent to these two values. To convert a value to the corresponding Boolean value, you can call the Transformation function Boolean () (In fact, Boolean, object,string,number,function, etc.) are all a function, a constructor, which can also be understood as a class, Calling the ToString () method with a type returns something like this:



function function () {[native code]}, function will be changed to the corresponding call function.



In fact, in the IF statement judgment, the inside conditions will automatically perform a Boolean change.



Number Type



Numeric types have many values, the most basic of course is the decimal, such as:



var num= 510;



In addition to the decimal, integers can also be octal or hexadecimal, where the octal literal first must be 0, followed by the octal number sequence, and if the value in the literal is out of range, the leading 0 will be ignored. The subsequent amount of the value will be parsed as a decimal number.



var num1=070;//octal 56
var num2 =079;//Invalid octal-Parse to 79
var num3 =08;//Invalid octal-Parse to 8



The hexadecimal front must be 0x, followed by a hexadecimal number (0~F), regardless of case. Such as:


var num1 = 0xA;
var num2 = 0x1f;


Although can be represented as octal and hexadecimal, the calculation is converted to decimal values.



In addition to integers, there are floating-point values, and of course, there is no such keyword as float in other strongly typed languages.


var NUM1 = 1.1;
var num2 =0.1;
var num3 =. 1;//valid, but not recommended


When you save an integer, the memory allocation size is only 1/2 of the floating-point number, so when floating-point numbers can be converted to integers, JavaScript is automatically converted to integers.



Of course, in addition to these small numbers, there are a number of large or small numbers, can be expressed in scientific notation,



var Num=123.456e10;



The highest precision of a floating-point number is 17 decimal digits, but the calculation is far less accurate than an integer. For example, 0.1+0.2 is not equal to 0.3, but 0.3000000000000004, so when making a judgment, do not use floating-point numbers to determine equal to the expected value.



The smallest value in JavaScript is Number.min_value, where it can be imagined that number is a class, and Min_value is a static variable that stores the minimum value, and the Number.MAX_VALUE is the largest.



If the calculation exceeds this maximum and the minimum range, it will be automatically converted to the Infinity value, if it is a negative number, that is-infinity, the whole number is infinity,infinity meaning infinity, that is, positive and negative infinity, and the concept of mathematics is the same. But infinity can not participate in the calculation. You can use the native function to determine if it is poor: Isfinite (); True is returned only in the range of values.



In JavaScript, in addition to those ordinary integers, floating-point numbers, maximum, minimum, infinity, there is a special value, that is, Nan. This value is used to indicate a case in which the operand that would have returned a numeric value did not return a numeric value. For example, any number divided by 0 in C # would be an error, throw an exception, but in JavaScript, any number divided by 0 would return Nan, so it would not affect the execution of the code.



Characteristics of Nan:



1. Any operation designed for Nan (e.g., nan/0) will return Nan.



2, Nan is not equal to any value, including the Nan itself. Such as:


Alert (nan = = nan);//false


So there's a isNaN () function in JavaScript that takes a parameter, any type, and it helps us determine if the parameter is "not numeric." It will first try to speak this value into a numerical number. A value that cannot be converted to a number returns true after the function is called, that is, the is NaN non-numeric.



As for numeric conversions, this content expands in JavaScript and is an article that has time to organize.



String type



Strings can be represented by either single or double quotes, which are equivalent in JavaScript, such as:


var name = ' Jwy ';
var author = "Jwy";


But just be aware of nesting correctly.



Strings can be assigned directly by literal values. The length of any string can be obtained by accessing the gas length property.



The strings in JavaScript are immutable, in fact this is the same as in C #, (presumably to improve performance), once the strings are created, their values cannot be changed, and to change the string that a variable holds, the first thing to do is to destroy the original string, Then fill the variable with another string containing the stationery.


var name= "Jwy";
Name = "Jwy" + "study JavaScript";


Here first name is to save the string "Jwy", the second line of code will be "Jwy" + "study JavaScript"; Value is assigned to name, which first frames a new string that can hold the length, and then fills and destroys the original string.



Almost every value has its own ToString () method, and the following article explains where the method came from and returns the string representation of the corresponding value.


var age=11;
var agetostring =age.tostring ();//"11"


Values, Boolean values, objects, and string values all have ToString (), but null and undefined values do not have this method.



In general, calling the ToString () method does not have to pass arguments, but when calling a numeric ToString method, you can pass a parameter that specifies the cardinality of the numeric value to output (see To Output decimal, binary, octal, hexadecimal representations)



Because null and undefined do not have the ToString method, the call is an error if it is not known whether it is the two, so there is another way to choose, which is to use the transformation function string (), it can receive any type of value into a string, the processing rules are as follows:



1. If this value has ToString then call directly and return the result



2, if it is null, then return "null"



3, if it is unde, then return to "undefined"



Object type



The object type is the originator of the JavaScript reference type (as it is in C # and Java), and you can add properties and methods to it after you create an instance of type object.


var o = new object;//is valid and does not recommend
var o =new Object ();


In JavaScript, any properties and methods of the object type also exist in more specific objects.



Each instance has the following properties and methods, as follows:



1, constructor, save the function used to create the current object. The constructor above is object ();



2, hasOwnProperty, to check whether a given property is in the current object instance, is true, not in the instance, but in the prototype, false;



3, isprototypeof, to check if the incoming object is another object's prototype



4, propertyisenumerable, to check whether a given property can be enumerated using the for...in statement,



5, ToString, return the string representation of the object



6, valueof, returns the string, numeric, or Boolean value of the object, usually the same as the ToString method return value



These are the properties and methods that object has, and all objects inherit these properties and methods because of the inheritance relationship.



Conclusion



Undefined, Null, Boolean, number, string are the basic data types in JavaScript, and object is a reference type. Detecting other types with typeof returns the corresponding string, but when the null or object is detected, it returns "Object", which, if mastered, will not be able to see the dots. Incidentally, I would say:



These three Boolean, number, and String are the basic wrapper types in JavaScript, which means that these three are actually a constructor, they are instances of function, are reference types, The string here is the same as the string in the article because in fact the string mentioned above refers to the string, where the string refers to this constructor of string, which is written to better understand because JavaScript is loosely typed. We can look at the example of string instantiation:


var name = String ("Jwy");
Alert (typeof name);//"Object"
var author = "Tom";
Alert (typeof name);//"string"


As for author, this is going to have length,substring and so on. These methods, in fact, are string here, string is just an instance of string, similar to string in C #, and string, only a bit special here.



Note that the typeof variable if the value is "string", that is, the variable is a string, in JavaScript, the string is the base type, whereas in C # or Java, the string is a reference type, but a string in JavaScript is a reference type. Because it is the basic wrapper type defined in JavaScript, in C #, a string is actually the same as a string. This thing is a bit round, if wrong, please point out, exchange and exchange.



Value types and reference types in JavaScript



One, embrace JavaScript



The once-well-known JavaScript has multiplied with the popularity of Ajax, and now JavaScript is no longer just a dispensable helper in web development, and even has a "JavaScript engineer" dedicated to its position, If you're just a web developer, you have to understand JavaScript, and at least you can see the word "familiar with JavaScript first" in some of the relevant job requirements. Even I have to tell you that you will be able to develop desktop software with JavaScript, thanks to another development model of Adobe AIR, which uses html+css+javascript to develop air.



Second, value type and reference type topic



As some of the major object-oriented language base friends intervene, they try to use JavaScript to simulate the various features of the surface objects, although some of the simulation is far-fetched, but also let us see the power and flexibility of JavaScript. JavaScript object-oriented Programming technology is not discussed in this paper. Just talk about two types of variables in javascript: that is, value types and reference types, which usually remind you of "stacks," plus "reference address" or "pointer" concepts, and people with experience in Java or C # programming believe that these two types are not unfamiliar. Here are some examples of how these two types of JavaScript are embodied, used, and noted.



What are the JavaScript value types and reference types



(1) value type: Numeric, Boolean, null, undefined.



(2) Reference type: object, array, function.



Iv. How to understand value types and reference types and examples



We can use "chain stores" and "Chain Keys" to understand, do not know the following analogy is not appropriate, ^-^.



(1) Value type Understanding: The exchange of variables is equal to a new place in accordance with the standard of the chain store (Unified store to understand the same variable content) a new branch, so that the newly opened shop and other old stores are not related to each other and operate.



Value type Example


function Chainstore ()
{
  var store1= ' Li-Ning ';
  var store2=store1;
  Store1= ' Li-Ning China '
  alert (Store2); Li-Ning chainstore ();
When you pass a value type (which can also be called a base type) Store2 to another variable (Assignment), in fact, a new memory space is allocated, so changing the value of Store1 has no effect on Store2 because it is not like a reference type, and the exchange of variables is actually an exchange of addresses that refer to the same content.


(2) Reference type Understanding: The exchange of variables equals the key of the existing store (variable reference address) copy one to the other boss, when two bosses manage a shop at the same time, and the behavior of two bosses can have an impact on the operation of a store.



Reference type Example



function Chainstore ()
{
  var store1=[' Li-Ning '];
  var store2=store1;
  Alert (store2[0]); Li-Ning store1[0]= ' Li-Ning China ' 
Alert (store2[0]); Li-Ning China

}
Chainstore ();
In the above code, Store2 only one assignment, theoretically its value has been fixed, but later by rewriting the Store1 value, found that Store2 value has also changed, which is the characteristics of the reference type, but also we should pay attention to the place.





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.