Basic JavaScript knowledge-data type_basic knowledge

Source: Internet
Author: User
Tags hasownproperty
JavaScript has five simple data types (also known as basic data types): Undefined, Null, Boolean, Number, and String. There is also a complex data type-Object, which is essentially a data type consisting of a group of unordered name-value pairs.
JavaScript has five simple data types (also known as basic data types): Undefined, Null, Boolean, Number, and String. There is also a complex data type-Object, which is essentially composed of a group of unordered name-value pairs.

Typeof Operator

JavaScript is loose, so a method is required to detect the Data Type of a given variable-typeof is the operator responsible for provider information. Using the typeof operator for a value may return one of the following strings:

● "Undefined" -- if this value is not defined;

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

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

● "Number" -- if this value is a value;

● "Object" -- if the value is an object or null;

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

Undefined type
The Undefined type has only one value, that is, the special undefined. When var is used to declare a variable but it is not initialized, the value of this variable is undefined. For example:

The Code is as follows:


Var message;
Alert (message = undefined) // true


Null type
Null is the second data type with only one value. This special value is null. Logically, the null value indicates a null object Pointer, which is exactly why "object" is returned when the typeof operator is used to detect null. For example:

The Code is as follows:


Var car = null;
Alert (typeof car); // "object"


If the defined variable is to be used to save the object in the future, it is better to initialize the variable to null instead of other values. In this way, as long as the null value is detected, you can know whether the corresponding variable has saved an object reference. For example:

The Code is as follows:


If (car! = Null)
{
// Perform some operations on the car object
}


In fact, undefined values are derived from null values, so the ECMA-262 specifies that true is returned for their equality tests.

The Code is as follows:


Alert (undefined = null); // true


Although null and undefined have such a relationship, their usage is completely different. No matter under any circumstances, it is unnecessary to explicitly set the value of a variable to undefined, but the same rule is not applicable to null. In other words, as long as the variable to save the object has not actually saved the object, it should be explicitly made to save the null value of the variable. This will not only reflect the Convention that null acts as a null Object Pointer, but also help to further differentiate null and undefined.

Boolean Type

This type has only two nominal values: true and false. These two values are not the same as numerical values, so true is not necessarily equal to 1, and false is not necessarily equal to 0.

Although there are only two literal values of the Boolean type, all types of values 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:

The Code is as follows:


Var message = 'Hello world ';
Var messageAsBoolean = Boolean (message );


In this example, the message string is converted to a Boolean value, which is saved in the messageAsBoolean variable. You can call the Boolean () function for values of any data type, and a Boolean value is always returned. Whether the returned value is true or false depends on the Data Type of the value to be converted and the actual value. The following table shows the conversion rules for various data types and their objects.


These conversion rules are very important for understanding how flow control statements (such as if statements) automatically execute corresponding Boolean conversions. For example:

The Code is as follows:


Var message = 'Hello world ';
If (message)
{
Alert ("Value is true ");
}


Run this example to display a warning box, because the string message is automatically converted to the corresponding Boolean value (true ). Because of this automatic Boolean conversion, it is critical to know exactly what variables are used in a flow control statement.
Number Type
This type is used to represent integers and floating point values. There is also a special value, that is, NaN (non-value Not a Number ). This value is used to indicate a situation where the operand that originally returns a value does not return a value (this will not throw an error ). For example, in other programming languages, dividing any number by 0 will lead to an error and thus stop code execution. However, in JavaScript, if any value is divided by 0, NaN is returned, so the execution of other code is not affected.
NaN has two extraordinary characteristics. First, any operation involving NaN (such as NaN/10) will return NaN, which may cause problems in multi-step computing. Secondly, NaN is not equal to any value, including NaN itself. For example, the following code returns false.
Alert (NaN = NaN); // false
JavaScript has an isNaN () function, which accepts a parameter that can be of any type, and the function will help us determine whether the parameter is "not a value ". After receiving a value, isNaN () tries to convert the value to a value. Some non-numeric values are directly converted to numeric values, such as the string "10" or Boolean value. Any value that cannot be converted to a value will cause this function to return true. For example:

The Code is as follows:


Alert (isNaN (NaN); // true
Alert (isNaN (10); // false (10 is a value)
Alert (isNaN ("10"); // false (may be converted to a value of 10)
Alert (isNaN ("blue"); // true (cannot be converted to a value)
Alert (isNaN (true); // false (may be converted to value 1)


There are three functions that can convert non-numeric values to numeric values: Number (), parseInt (), and parseFloat (). The first function, that is, the transformation function Number (), can be used for any data type, and the other two functions are specifically used to convert a string to a value. These three functions return different results for the same input.
The conversion rules of the Number () function are as follows:
● If it is a Boolean value, true and false will be replaced with 1 and 0 respectively.
● If it is a numeric value, it is simply passed in and returned
● If the value is null, 0 is returned.
● If it is undefined, NaN is returned.
● If it is a string, follow the following rules:
○ If a string contains only numbers, convert it to a decimal value, that is, "1" will be 1, "123" will be 123, and "011" will change to 11 (leading 0 is ignored)
○ If a string contains a valid floating point format, such as "1.1", it is converted to the corresponding floating point number (similarly, leading 0 is ignored)
○ If a string contains a valid hexadecimal format, for example, "0xf", convert it to a decimal integer of the same size.
○ If the string is empty, convert it to 0.
○ If a string contains characters other than the preceding format, convert it to NaN
● If it is an object, call the valueOf () method of the object and convert the returned value according to the previous rules. If the conversion result is NaN, call the toString () method of the object, and convert the returned string values in sequence according to the preceding rules.

The Code is as follows:


Var num1 = Number ("Hello World"); // NaN
Var num2 = Number (""); // 0
Var num3 = Number ("000011"); // 11
Var num4 = Number (true); // 1


Because the Number () function is complex and not reasonable enough to convert strings, parseInt () is more commonly used when processing integers. When converting a string, the parseInt () function depends more on whether it complies with the value mode. It ignores spaces before the string until the first non-space character is found. If the first string is not a numeric character or a negative number, parseInt () returns NaN; that is, if parseInt () is used to convert the Null String, NaN is returned. If the first character is a numeric character, praseInt () will continue to parse the second character, knowing that all subsequent characters have been parsed or that a non-numeric character has been encountered. For example, "1234 blue" is converted to 1234, and "22.5" is converted to 22 because the decimal point is not a valid number character.
If the first character in a string is a numeric character, parseInt () can also recognize various integer formats (decimal, octal, and hexadecimal ). To better understand the conversion rules of the parseInt () function, the following examples are provided:

The Code is as follows:


Var num1 = parseInt ("1234 blue"); // 1234
Var num2 = parseInt (""); // NaN
Var num3 = parseInt ("0xA"); // 10 (hexadecimal)
Var num4 = parseInt ("22.5"); // 22
Var num5 = parseInt ("070"); // 56 (octal)
Var num6 = parseInt ("70"); // 70
Var num7 = parseInt ("10", 2); // 2 (parsed by binary)
Var num8 = parseInt ("10", 8); // 8 (parsed by octal)
Var num9 = parseInt ("10", 10); // 10 (parsed in decimal format)
Var num10 = parseInt ("10", 16); // 16 (in hexadecimal format)
Var num11 = parseInt ("AF"); // 56 (octal)
Var num12 = parseInt ("AF", 16); // 175


Similar to the parseInt () function, parseFloat () parses each character from the first character (position 0. It is resolved to the end of the string, or to an invalid floating-point numeric character. That is to say, the first decimal point in the string is valid, and the second decimal point is invalid. Therefore, the string following it will be ignored. For example, "22.34.5" will be converted to 22.34.
The second difference between parseFloat () and parseInt () is that it always ignores the leading zero. Because the parseFloat () value resolves the decimal value, it does not use the second parameter to specify the base.

The Code is as follows:


Var num1 = parseFloat ("1234 blue"); // 1234
Var num2 = parseFloat ("0xA"); // 0
Varnum3 = parseFloat ("22.5"); // 22.5
Var num4 = parseFloat ("22.34.5"); // 22.34
Varnum5 = parseFloat ("0908.5"); // 908.5


String type
The String type is used to represent a String that consists of zero or multiple 16-bit Unicode characters. A string can be expressed by single quotation marks (') or double quotation marks.

The Code is as follows:


Var str1 = "Hello ";
Var str2 = 'hello ';


The length of any string can be obtained by accessing its length attribute.

The Code is as follows:


Alert (str1.length); // output 5


There are two methods to convert a value to a string. The first method is to use the toString () method that almost every value has.

The Code is as follows:


Var age = 11;
Var ageAsString = age. toString (); // string "11"
Var found = true;
Var foundAsString = found. toString (); // string "true"


Values, Boolean values, objects, and string values all have the toString () method. But null and undefined values do not have this method.
In most cases, parameters are not required to call the toString () method. However, when calling the toString () method of a value, you can pass a parameter: The base number of the output value.

The Code is as follows:


Var num = 10;
Alert (num. toString (); // "10"
Alert (num. toString (2); // "1010"
Alert (num. toString (8); // "12"
Alert (num. toString (10); // "10"
Alert (num. toString (16); // ""


In this example, we can see that by specifying the base, the toString () method will change the output value. The value 10 can be converted to different numeric formats during output based on the different base numbers.
If you do not know whether the value to be converted is null or undefined, you can also use the transformation function String (), which can convert any type of value to a String. The String () function follows the following conversion rules:
● If the value has a toString () method, call this method (without parameters) and return the corresponding result.
● If the value is null, "null" is returned"
● If the value is undefined, "undefined" is returned.

The Code is as follows:


Var value1 = 10;
Var value2 = true;
Var value3 = null;
Var value4;
Alert (String (value1); // "10"
Alert (String (value2); // "true"
Alert (String (value3); // "null"
Alert (String (value4); // "undefined"


Object Type
Objects are actually a set of data and functions. An object can be created by executing the new operator and the name of the object type to be created. You can create a custom Object by creating an instance of the Object type and adding its attributes and (or) methods.

The Code is as follows:


Var o = new Object ();


Each instance of an Object has the following attributes and methods:
● Constructor -- stores the function used to create the current object.
● HasOwnProperty (propertyName) -- used to check whether a given property exists in the current object instance (rather than in the instance's prototype. The parameter property name must be specified as a string (for example, o. hasOwnProperty ("name "))
● IsPrototypeOf (object) -- used to check whether the input object is a prototype of another object
● PropertyIsEnumerable (propertyName) -- used to check whether a given attribute can be enumerated using the for-in statement.
● ToString () -- returns the string representation of the object
● ValueOf () -- returns the string, value, or Boolean value of the object. It is usually the same as the return value of the toString () method.
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.