Deep understanding of JavaScript data types

Source: Internet
Author: User
Tags first string

The data types in JavaScript fall into two categories: primitive and Object types. The primitive types include undefined, Null, Boolean, number, and string, except for those types of objects.

NULL type

Null is a keyword in the JavaScript language that represents a special value that is commonly used to denote "null", executes the typeof operator on NULL, and returns the string "Object", which means that null can be thought of as a special object value, meaning "non-object". But in fact, it is generally assumed that NULL is the only member of his own type, and that he can represent numbers, strings and objects as "no value"

  var NULL ;  Console.log (typeof//  "Object"
Undefined type

The

Undefined is the second value of JavaScript that represents a vacancy, with an undefined value representing a deeper "empty value," which is a value of the variable, indicating that the variable is not initialized, If the value of the object property or array element to be queried returns undefined, the property or element does not exist, and if the function does not have any return value, undefined is returned. Use the typeof operator to return undefined, indicating that the value is the only member of this type. Although null and undefined are different, they all represent the vacancy of values, which are often interchangeable, and the judge "= =" thinks the two are equal (requires "= = =" to differentiate them).

var Carconsole.log (car); // "undefined"console.log (typeof car); // "undefined" function Test () {    return;} Console.log (Test ())//"undefined"null); // true null); // false
Boolean type

The

Boolean value represents true or false. This type has only two values: True and false. Although there are only two literals of the Boolean type, all types in JavaScript have values that are equivalent to these two Boolean values. To convert a value to its corresponding Boolean value, you can call the type conversion function Boolean (). Undefined,null,0,-0,nan, "will be converted to false, and all other values will be converted to true.

 var  a = " var  b = null   var  C = 0;  var  D = NaN;  var   E;console.log (Boolean (a));  // false  Console.log (Boolean (b)); // false  Console.log (Boolean (c)); // false  Console.log (Boolean (d)); // false  Console.log (Boolean (e)); // false  
Number Type

This type is used to represent integers and floating-point numbers, and there is a special value, Nan (non-numeric not a number). This value is used to indicate that an operand that would have returned a numeric value does not return a numeric value (so that no error is thrown). For example, in other programming languages, dividing any number by 0 will result in an error, thereby stopping code execution. In JavaScript, however, any number divided by 0 returns Nan, so it does not affect the execution of other code. The Nan itself has two unusual features. First, any operation involving Nan, such as NAN/10, will return Nan, a feature that can cause problems in a multi-step calculation. Second, Nan is not equal to any value, including the Nan itself. For example, the following code returns false.

Alert (nan = = nan);    // false

There is a isNaN () function in JavaScript that takes a parameter that can make any type, and the function will help us determine whether the parameter is "not a value". IsNaN () after receiving a value, it attempts to convert the value to a number. Some values that are not numeric are converted directly to numeric values, such as the string "10" or the Boolean value. Any value that cannot be converted to a number will cause the function to return true. For example:

   Alert (IsNaN (NaN));    // true    Alert (IsNaN (ten));    // False (10 is a numeric value)    Alert (IsNaN ("ten"));    // False (may be converted to a value of ten)    Alert (IsNaN ("Blue"));    // true (cannot be converted to numeric value)    Alert (IsNaN (true));    // False (may be converted to a value of 1)

There are 3 functions that can convert non-numeric values to numeric values: Number (), parseint (), and parsefloat (). The first function, the transformation function number (), can be used for any data type, while the other two functions are specifically used to convert a string into a numeric value. These 3 functions return different results for the same input.

The conversion rules for the number () function are as follows:

If it is a Boolean value, True and false are replaced with 1 and 0, respectively

If it is a numeric value, simply pass in and return

If it is a null value, returns 0

If it is undefined, return Nan

If it is a string, follow these rules:

0 If the string contains only numbers, it is converted to a decimal value, that is, "1" becomes 1, "123" becomes 123, and "011" becomes 11 (leading 0 is ignored)

0 If the string contains a valid floating-point format, such as "1.1", it is converted to the corresponding floating-point number (also ignoring the leading 0)

0 If the string contains a valid hexadecimal format, such as "0xf", it is converted to a decimal integer value of the same size

0 If the string is empty, convert it to 0

0 If the string contains characters other than the above format, convert it to Nan

if it is an object, the valueof () method of the object is called, and the returned value is converted according to the preceding rule. If the result of the conversion is Nan, the object's ToString () method is called, and then the returned string value is converted in turn by the preceding rule.

  var num1 = number ("Hello world");    // NaN    var num2 = number ("");                // 0    var num3 = number ("000011");        //  One    var num4 = number (true);            // 1

Because the number () function is complex and unreasonable when converting strings, the parseint () function is more commonly used when working with integers. The parseint () function converts a string more to see whether it conforms to a numeric pattern. It ignores the spaces in front of the string until the first non-whitespace character is found. If the first string is not a numeric character or minus sign, parseint () returns Nan, that is, converting an empty string with parseint () returns Nan. If the first character is a numeric character, Praseint () continues to parse the second character, knowing that all subsequent characters are parsed or a non-numeric character is encountered. For example, "1234blue" is converted to 1234 and "22.5" is converted to 22 because the decimal point is not a valid numeric character.

If the first character in a string is a numeric character, parseint () can also recognize various integer formats (that is, decimal, octal, hexadecimal). To better understand the conversion rules of the parseint () function, here are some examples

 varNUM1 = parseint ("1234blue");//1234 varnum2 = parseint ("");//NaN varnum3 = parseint ("0xA");//10 (hex) varNUM4 = parseint ("22.5");// A varNUM5 = parseint ("070");//56 (octal) varNUM6 = parseint ("70");// - varNUM7 = parseint ("10", 2);//2 (by binary parsing) varNUM8 = parseint ("10", 8);//8 (parsing by octal) varNUM9 = parseint ("10", 10);//10 (resolution by decimal) varNUM10 = parseint ("10", 16);//16 (parsing by hexadecimal) varNUM11 = parseint ("AF");//56 (octal) varNUM12 = parseint ("AF", 16);//175

Like the parseint () function, parsefloat () also parses each character starting with the first character (position 0). It is also parsed until the end of the string, or until an invalid floating-point numeric character is encountered. That is, the first decimal point in the string is valid, and the second decimal point is invalid, so the string following it is ignored. For example, "22.34.5" will be converted to 22.34.

The second difference between parsefloat () and parseint () is that it will always ignore the leading 0. Because the parsefloat () value resolves a decimal value, it does not specify the usage of the cardinality with the second argument.

  var num1 = parsefloat ("1234blue");    // 1234  var num2 = parsefloat ("0xA");        // 0  var num3 = parsefloat ("22.5");        // 22.5  var num4 = parsefloat ("22.34.5");    // 22.34  var num5 = parsefloat ("0908.5");    // 908.5
String type

The string type is used to represent a sequence of characters consisting of 0 or more 16-bit Unicode characters, the string. The string can be represented by a single quotation mark (') or double quotation mark ("). A string bounded by single quotation marks can contain double quotation marks, and a string bounded by double quotation marks can contain single quotes. You can also split a string into multiple lines, with each line ending with a backslash. Like what

var str1 = ""; var str2 = ' Test '; var str3 = ' 3.14 '; var str4 = ' wound you like ' javascript '? ' var str5 = 'wound             you '

Javasript has a string-based connection, and if the expression contains a string, the string can be stitched together by the plus operator. For a value that is not a string, it is first converted to a string and then spliced.

var str1 = ' Hello ' + ' world ';   // "Hello World" var str2 = ' 1 ' + 1;          //  One var true + ' false ';     // "TrueFalse"

Strings have many methods that can be called (all methods can be viewed through string.prototype).

varstr = "Hello World"Str.length//11, String lengthStr.charat (0)//' H ', the first characterStr.charat (str.length-1)//' d ', the last characterStr.substring (1,4)//' ell ', 第2-4 charactersStr.slice (1,4)//' ell ', ibid.S.indexof (' l ')//2, the position of the first occurrence of the character LStr.split (")//["Hello", "World"], split stringstr.__proto__//String Prototype ObjectString.prototype//Ibid .
Object type

Except for the above types are objects, including arrays, functions, objects, regular, and so on are object types. An object is actually a set of data and functions. An object can be created by executing the new operator followed by the name of the object type to be created. You can create a custom object by creating an instance of type object and adding properties and/or methods to it. You can also create objects by using the direct amount of the object, which is a mapping table that consists of several key-value pairs, or you can create objects from the object's Create method. Objects are unique, regardless of the method by which the objects are created are not equal.

var obj1 = {};                    // Empty Object var New Object ();        // Empty Object var obj3 = object.create (null// null object varnew  = = obj4)         //false

Each instance of an object type has many methods. You can view all the methods of an object through Object.prototype.

varobj =NewObject (); obj.tostring ()//[Object,object], convert to StringObj.title = ' Hello '//Add PropertyObject.defineproperty (obj, ' title ', {value:' Hello ', writable:true, Enumerable:true, Configurable:true})                    //Ibid .Obj.valueof ()//an object that returns the primitive values of the objects. obj.__proto__//Object PrototypesObject.prototype//Ibid .

Deep understanding of JavaScript data types

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.