JavaScript data types

Source: Internet
Author: User
Tags first string hasownproperty

Original: JavaScript data type

Data type

There are 5 simple data types (also known as basic data types) in javascript: Undefined, Null, Boolean, number, and string. There are 1 more complex data types--object,object essentially consist of a set of unordered name-value pairs.

typeof operator

While JavaScript is loosely typed, there needs to be a means to detect the data type of a given variable--typeof is the operator that is responsible for the provider aspect information. Using the typeof operator on a value may return one of the following strings:

"Undefined"--if this value is undefined;

"Boolean"--if this value is a Boolean value;

"String"--if the value is a string;

"Number"--if the value is numeric;

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

"Function"--if the value is a function;

Undefined type

The undefined type has only one value, that is, a special undefined. When you declare a variable using var but do not initialize it, the value of the variable is undefined, for example:

    var message;    Alert (message = = undefined)//true
Null type

The null type is the second data type with only one value, and this special value is null. From a logical point of view, a null value represents an empty object pointer, which is why "object" is returned when using the TypeOf operator to detect NULL, for example:

    var car = null;    Alert (typeof car); "Object"

If a defined variable is intended to be used to hold an object in the future, it is better to initialize the variable to null instead of to another value. This way, you can know if the corresponding variable has saved a reference to an object as long as you directly detect the null value, for example:

    if (car! = null)    {        //Perform some action on the car object    }

In fact, the undefined value is derived from a null value, so ECMA-262 specifies that the equality test for them returns true.

alert (undefined = = null); True

Although null and undefined have such relationships, their use is completely different. In any case, it is not necessary to explicitly set the value of a variable to undefined, but the same rule does not apply to NULL. In other words, as long as the variable that is intended to hold the object does not actually hold the object, you should explicitly let the variable hold the null value. Doing so not only manifests null as a convention for null object pointers, but also helps to further differentiate between null and undefined.

Boolean type

The type has only two literals: true and false. These two values are not the same as numeric values, so true does not necessarily equal 1, and false does not necessarily equal 0.

Although there are only two literals of the Boolean type, the values of all types in JavaScript have values equivalent to these two Boolean values. To convert a value to its corresponding Boolean value, you can call the type conversion function Boolean (), for example:

    var message = ' Hello world ';    var Messageasboolean = Boolean (message);

In this example, the string message is converted to a Boolean value that is stored in the Messageasboolean variable. You can call the Boolean () function on a value of any data type, and always return a Boolean value. The value returned is true or false, depending on the data type of the value to be converted and its actual value. The following table shows the conversion rules for various data types and their objects.

These translation rules are important for understanding flow control statements, such as if statements, to automatically perform a corresponding Boolean conversion, such as:

    var message = ' Hello world ';    if (message)    {        alert ("Value is true");    }

Running this example, a warning box is displayed because the string message is automatically converted to the corresponding Boolean value (TRUE). Because of this automatic Boolean conversion, it is important to know exactly what variables are used in flow control statements.

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)    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    -by-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

    var num1 = parseint ("1234blue");    1234    var num2 = parseint ("");            NaN    var num3 = parseint ("0xA");            10 (hex)    var num4 = parseint ("22.5");    var num5 = parseint ("070");            56 (octal)    var num6 = parseint ("n");            The    var num7 = parseint ("Ten", 2);        2 (by binary parsing)    var num8 = parseint ("Ten", 8);        8 (parsing by octal)    var num9 = parseint ("ten");        10 (by decimal resolution)    var NUM10 = parseint ("ten", +);        16 (by hex)    var num11 = parseint ("AF");            56 (octal)    var num12 = parseint ("AF", +);        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 (").

    var str1 = "Hello";    var str2 = ' Hello ';

The length of any string can be obtained by accessing its long property

alert (str1.length);        Output 5

There are two ways to convert a value to a string. The first is the ToString () method, which uses almost every value.

    var age = one;    var ageasstring = age.tostring ();    The string "one"    var found = true;    var foundasstring = found.tostring ();    String "true"

Numeric, Boolean, object, and string values have the ToString () method. However, the null and undefined values do not have this method.

In most cases, calling the ToString () method does not have to pass arguments. However, when you call the ToString () method of a number, you can pass a parameter: the cardinality of the output value.

    var num = ten;    Alert (num.tostring ());      "Ten"    Alert (num.tostring (2));     "1010"    Alert (num.tostring (8));    alert (num.tostring);    "Ten"    alert (num.tostring);    A

This example shows that by specifying the cardinality, the ToString () method changes the value of the output. The value 10, depending on the cardinality, can be converted to a different numeric format at output.

You can also use the Transform function string (), which can convert any type of value to a string, without knowing that the value to be converted is null or undefined. The String () function follows the following translation rules:

If the value has the ToString () method, the method (with no arguments) is called and the corresponding result is returned

Returns "NULL" if the value is null

Returns "Undefined" if the value is undefined

    var value1 = ten;    var value2 = true;    var value3 = null;    var value4;    Alert (String (value1));    "Ten"    Alert (String (value2));    "True"    alert (String (VALUE3));    "Null"    alert (String (VALUE4));    "Undefined"
Object type

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.

var o = new Object ();

Each instance of object has the following properties and methods:

constructor--holds the function for creating the current object

hasOwnProperty (PropertyName)--Used to check for the existence of a given property in the current object instance, rather than in the prototype of the instance. where the attribute name (PropertyName) as a parameter must be specified as a string (for example: O.hasownproperty ("name"))

isPrototypeOf (object)--Used to check if an incoming object is a prototype of another object

propertyIsEnumerable (PropertyName)--Used to check whether a given property can use the For-in statement to enumerate

ToString ()--Returns the string representation of an object

ValueOf ()--Returns the string, numeric, or Boolean representation of the object. Usually the same as the return value of the ToString () method.

JavaScript data types

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.