We often see some data types in javascript, such as "undefined", "boolean", and "string, this article will help you learn the basic JavaScript data types, value types, and reference types. For more information, see this article, four basic data types in JavaScript: Numeric (integer and real), string (character or value enclosed by a "" sign or), Boolean (expressed by True or False), and null. Data in the basic JavaScript type can be constants or variables. JavaScript uses a weak type, so a data variable or constant does not need to be declared first. Instead, it determines the data type when using or assigning values. Of course, you can also declare the Data Type first. It automatically describes the data type when assigning values.
Javascript Variables
The variables in javascript are just placeholders, as described in the preface, because of the loose type.
Define variables:
Var name;
The code above defines a variable named name, which can be used to save any value (such uninitialized variable will save a special value -- undefined ), you can also initialize the value of a variable,
Var name = "y"; // There is no difference between single quotes and double quotes in javascript, but note that the correct nested name = 10;
At the beginning, the name is initialized to the string value "Y", and then changed to the numeric value-100. This method is not recommended, but it is effective in ECMAScript, in addition, this is often done.
You can also define multiple variables in one statement, and many javascript frameworks do this.
var name=”jwy”,author,age=29;
Adding points to each statement is a good programming habit. However, we recommend that you wrap and indent multiple variables to improve readability.
Simple data type
ECMAScript has five simple data types: Undefined, Null, Boolea, Number, and String. There is also a complex data type-Object
Typeof Operator
Because the variables in Javascript are loose, it provides a method to detect the Data Type of the current variable, that is, the typeof keyword, among the five simple data types in ECMAScript mentioned above, (Remember, these five are only data types, representing a data type, just think of int in C, string type). The following values are returned for these five data types using the typeof keyword (displayed as strings ).
"Undefined" ---------- if the value is Undefined
"Boolean" ---------- if this value is a Boolean Value
"String" ---------- if the value is a String
"Number" ---------- if this value is of the numerical type Number
"Object" ---------- if this value is an Object or null object
"Function" ---------- if this value is a Function function
Strictly speaking, a Function is an object in ECMAScript. Each Function is an instance of the Function class. Since a Function is an object, it is also a reference type, therefore, a function is just a variable name. Therefore, it is often seen in many cases that the function name is passed into the function as a parameter and then called, which is similar to the delegate in C, the function will be explained in detail later. After all, many things in Javascript depend on functions for implementation.
Undefined type
As mentioned above, five data types are data types, so the data type has a value. The Undefined value is undefined. Note that u is lowercase. If the declared variable is not initialized, the value of the current variable is undefined. However, we recommend that you initialize variables as much as possible, but the undefined value is not specified in earlier Javascript versions. Therefore, in some frameworks, to be compatible with earlier browsers, the undefined value is added to the window object as follows:
Window ['undefined'] = window ['undefined']; // or window. undefined = window. undefined;
Simply put, the undefined attribute of the window object is assigned with undefined. The undefined attribute does not exist in the older browser object. Therefore, undefined operations may cause exceptions, therefore, this method is adopted, but it may be difficult to understand at first, because there is no window in the browser of the old version. the undefined object returns an undefined value, so it is compatible with the old browser.
However, variables that contain undefined values are different from undefined variables, for example:
Var name; alert (name); // undefinedalert (age); // error: age is not defined
Variables that have not been declared can only perform one operation, but cannot do anything else, that is, they use the typeof operator to detect their data types.
If typeof is executed regardless of whether the declared and undeclared variables are declared, the undefined value is returned. Neither of the two methods can be used to perform real operations.
Null type
The Null value is null, which indicates a null Object Pointer and does not point to any object. If the value of a variable is Null, the current variable is probably a garbage collection object, when a null value is monitored using typeof, "object" is returned ",
var person = null;alert(typeof person);//”object”
Suggestion: If the variable is used to save the object's amount, it is initialized to null so that it can detect whether the variable has saved an object reference,
Note: The undefined value is derived from null. Therefore, true is returned when you perform the equality test on them, for example:
alert(null == undefind);//true
Despite this, they have completely different purposes. No matter under any circumstances is necessary to set the value of a variable to undefined, but this rule is not applicable 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 equivalent values. To convert a value to a corresponding Boolean value, you can call the transformation Function Boolean () (in fact, Boolean, Object, String, Number, Function, and so on are all a Function, constructor, it can also be understood as a class. Calling the toString () method with the type will return something like this:
"Function Function () {[native code]}", the Function will be changed to its own call function)
In fact, in the if statement judgment, Boolean changes will be automatically executed for the conditions in it.
Number Type
The numeric type has many values. The most basic value is decimal, for example:
Var num = 510;
In addition to decimal, integers can also be in octal or hexadecimal notation, where the first value of the octal character must be 0 and then the octal Character Sequence. If the value in the nominal value is out of the range, the leading zero is ignored. The subsequent numeric values are parsed as decimal numbers.
Var num1 = 070; // 56 of octal
Var num2 = 079; // invalid gossip-resolved to 79
Var num3 = 08; // invalid octal-resolved to 8
The hexadecimal format must be 0x followed by a hexadecimal number (0 ~ F), case insensitive. For example:
var num1 = 0xA;var num2 = 0x1f;
Although it can be expressed as octal and hexadecimal, it is converted to a decimal Value During computation.
Besides integers and floating point values, of course, there are no keywords such as float in other strong languages.
Var num1 = 1.1; var num2 = 0.1; var num3 =. 1; // valid, but not recommended
When an integer is saved, the memory allocation size is only 1/2 of the floating point number. Therefore, when the floating point number can be converted to an integer, javascript will automatically convert it to an integer.
Of course, in addition to the small values, there are some extremely large or extremely small values that can be expressed by scientific notation,
Var num = 123.456e10;
The highest precision of a floating point value is 17 decimal places, but its accuracy is far less than that of an integer. For example, 0.1 + 0.2 is not equal to 0.3, but 0.3000000000000004. Therefore, when making a judgment, do not use floating point numbers to sum up to determine whether it is equal to a value expected.
In javascript, the smallest value is Number. MIN_VALUE. Here we can imagine that Number is a class, while MIN_VALUE is a static variable, storing the minimum value. Similarly, the maximum value is Number. MAX_VALUE.
If the calculation exceeds the maximum and minimum values, it is automatically converted to the Infinity value. If it is a negative number, it is-Infinity, the integer is Infinity, and Infinity means Infinity, that is, positive and negative infinity is the same as the concept in mathematics. However, Infinity cannot be involved in computing. You can use the native function to determine whether it is poor: isFinite (); true is returned only when it is within the value range.
In Javascript, apart from common integers, floating point numbers, maximum values, minimum values, and infinity, there is also a special value, NaN. This value is used to indicate that the number of operations to return a value has not been returned. For example, if any value in C # is divided by 0, an error is thrown. However, in Javascript, if any value is divided by 0, Nan is returned, so code execution is not affected.
Features of NaN:
1. Any operation designed for NaN (for example, NaN/0) will return NaN.
2. NaN is not equal to any value, including NaN itself. For example:
alert(NaN == NaN);//false
Therefore, Javascript has an isNaN () function, which receives a parameter of any type and determines whether the parameter is "not a value ". It first tries to convert the value to a value. If a value that cannot be converted to a value is called, true is returned, that is, a non-numeric value of is NaN.
As for numeric conversion, this content is extended in Javascript and it is an article that will be sorted out later.
String type
Strings can be represented by single or double quotation marks. In Javascript, these two quotation marks are equivalent, for example:
var name = ‘jwy';var author = “jwy”;
But pay attention to correct nesting.
Strings can be directly assigned with a literal value. The length of any string can be obtained by accessing the gas length attribute.
Strings in Javascript are immutable. In fact, they are the same as those in C # (it is estimated that they are also used to improve performance). Once a string is created, their values cannot be changed, to change the string saved by a variable, first destroy the original string, and then fill the variable with another string containing the letter.
var name=”jwy”;name = “jwy”+” study javascript”;
At the beginning, the name is the string "Y", and the second line of code will "Y" + "study javascript"; the value will be assigned to the name again, it first mounts a new string that can hold this length, then fills in and destroys the original string.
Almost every value has its own toString () method. The subsequent articles will explain where this method comes from, and it will return 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 use this method.
Generally, you do not need to pass parameters when calling the toString () method. However, when calling the value toString method, you can pass a parameter, it is used to specify the base number of the value to be output (in decimal, binary, octal, and hexadecimal notation)
Since null and undefined do not have the toString method, an error is returned when you do not know whether the two methods are used. Therefore, you can choose to use the transformation function String (), it can convert any type of value into a string. The processing rules are as follows:
1. If this value has toString, it is called directly and the result is returned.
2. If it is null, "null" is returned"
3. For unde, "undefined" is returned"
Object Type
The Object type is the originator of the Javascript reference type (just like in C # and Java). After creating an Object-type instance, you can add attributes and methods to it,
Var o = new Object; // valid. var o = new Object () is not recommended ();
In Javascript, any attributes and methods of the Object type also exist in more specific objects.
Each instance has the following attributes and methods:
1. constructor: stores the function used to create the current object. The above constructor is Object ();
2. hasOwnProperty is used to check whether the given property is in the current object instance. It is true, not in the instance, but in the prototype, and false;
3. isPrototypeOf is used to check whether the input object is a prototype of another object.
4. propertyIsEnumerable: used to check whether a given property can use... In statement to enumerate,
5. toString: String Representation of the returned object
6. valueOf: returns the string, value, or Boolean value of the object, which is usually the same as the return value of the toString method.
The above are the attributes and methods of the Object. All objects inherit these attributes and methods because of the inheritance relationship.
Conclusion
Undefined, Null, Boolean, Number, and String are basic data types in javascript, and objects belong to reference types. If typeof is used to detect other types, a corresponding string will be returned, but "object" will be returned when null or object is detected. If you have mastered this, you will not be confused about this. The following is a reference:
Boolean, Number, StringThese three are the basic packaging types in Javascript, that is, these three are actually a constructor. They are Function instances and reference types, the String here is the same as the String mentioned in the article, because the String mentioned above actually refers to the String. Here the String refers to the String constructor, which is written as above, it is for better understanding, because Javascript is loose. Let's take a 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, there will be methods such as length and substring, which is actually the aspect of String here. string is just an instance of String, similar to String in C #, and string, but it is special here.
Note: If the value of typeof variable is "string", that is, the variable is a string. In Javascript, the string is of the basic type, and in C # or Java, string is a reference type, but String in Javascript is a reference type, because it is a basic packaging type defined in Javascript. in C #, string is actually the same as String. This is a bit difficult. If something is wrong, please point it out and communicate with each other.
Value Type and reference type in JavaScript
1. Embrace JavaScript
Once well-known JavaScript has doubled its value with the popularity of AJAX. Now JavaScript is no longer just a dispensable auxiliary tool in WEB development, but it even has its own position as a "JavaScript engineer ", even if you are just a WEB Background development programmer, you must understand JavaScript. At least you can see the word "familiar with JavaScript first" in some recruitment requirements. I even want to tell you that you can use JavaScript to develop desktop software, thanks to another development mode of Adobe AIR, that is, using HTML + CSS + JavaScript to develop AIR.
Ii. Value Type and reference type topic
With the intervention of some large object-oriented language-based friends, they tried to use JavaScript to simulate various features of the facial image object, although some of the simulation seems far-fetched, however, we have also seen the strength and flexibility of JavaScript. This article does not discuss JavaScript Object-Oriented Programming Technology for the moment. Let's talk about two types of variables in JavaScript: Value Type and reference type. This often reminds you of "stack ", there are also concepts related to "reference address" or "Pointer". Those who have experience in Java or C # programming are believed to be familiar with these two types. The following is an example of the embodiment, usage, and precautions of these two types in JavaScript.
Iii. JavaScript value types and reference types
(1) Value Type: numerical value, Boolean value, null, undefined.
(2) reference type: object, array, and function.
4. How to understand the value type and reference type and Examples
We can use "chain stores" and "Chain Store keys" to understand it. I don't know if the following metaphor is appropriate. ^-^.
(1) Value Type understanding: the exchange of variables is equivalent to opening a new branch in a new place according to the standard of the chain store (the unified store understands the same variable content, in this way, newly opened stores are irrelevant to other old stores and operate independently.
Value Type example
Function chainStore () {var store1 = 'nike China'; var store2 = store1; store1 = 'nike U. s. a. '; alert (store2); // Nike China} chainStore (); // when a value type (also known as the basic type) store2 is passed to another variable (assigned a value, in fact, a new memory space is allocated, so changing the store1 value has no effect on store2, because it is not similar to the reference type, the exchange of variables refers to the address of the same content.
(2) Understanding of the reference type: the exchange of variables is equivalent to copying the key (variable reference address) of the existing store to another boss. At this time, the two bosses manage the same store at the same time, the actions of both shopkeepers may affect the operation of a store.
Reference Type example
Function chainStore () {var store1 = ['nike China']; var store2 = store1; alert (store2 [0]); // Nike China store1 [0] = 'nike U. s. a. '; alert (store2 [0]); // Nike U. s. A .} chainStore (); // In the above Code, store2 only performs a value assignment once. Theoretically, its value has been set, but it is rewritten later by the store1 value, it is found that the value of store2 has also changed, which is the feature of the reference type, which is also worth attention.