Home > Web Front-end > JS Tutorial > Detailed explanation of JavaScript data types_Basic knowledge

Detailed explanation of JavaScript data types_Basic knowledge

WBOY
Release: 2016-05-16 16:06:31
Original
960 people have browsed it

Data Type

There are 5 simple data types (also called basic data types) in JavaScript: Undefined, Null, Boolean, Number and String. There is also a complex data type - Object. Object is essentially composed of a set of unordered name-value pairs.

typeof operator

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

● "undefined" - if the value is undefined;
● "boolean" - if the value is a boolean;
● "string" - if the value is a string;
● "number" - if the value is a numeric value;
● "object" - if the value is an object or null;
● "function" - if the value is a function;

Undefined type

The Undefined type has only one value, the special undefined. When a variable is declared using var but is not initialized, the value of the variable is undefined, for example:

Copy code The code is as follows:

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, the null value represents a null object pointer, and this is why "object" is returned when using the typeof operator to detect null, for example:

Copy code The code is as follows:

var car = null;
alert(typeof car); // "object"

If you define a variable that is going to be used to hold an object in the future, it is best to initialize the variable to null rather than to another value. In this way, you can know whether the corresponding variable already holds a reference to an object by directly detecting the null value, for example:
Copy code The code is as follows:

if(car != null)
{
​​​​ //Perform certain operations on the car object
}

In fact, the undefined value is derived from the null value, so ECMA-262 stipulates that their equality test should return true.

Copy code The code is as follows:

alert(undefined == null); //true

Although null and undefined have this relationship, their uses are completely different. Under no circumstances is it 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 a variable that is intended to hold an object does not actually hold an object, you should explicitly let the variable hold a null value. Doing so not only reflects the convention of null as a null object pointer, but also helps to further distinguish null and undefined.

Boolean type

This type has only two literal values: true and false. These two values ​​are not the same thing as numeric values, so true does not necessarily equal 1 and false does not necessarily equal 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:

Copy code The code is as follows:

var message = 'Hello World';
var messageAsBoolean = Boolean(message);

In this example, the string message is converted into a Boolean value, which is stored in the messageAsBoolean variable. The Boolean() function can be called on a value of any data type and will always return a Boolean value. As for whether the returned value is true or false, it depends on the data type of the value to be converted and its actual value. The following table gives the conversion rules for various data types and their objects.

These conversion rules automatically perform corresponding Boolean conversion for understanding flow control statements (such as if statements)

It is very important to change, for example:

Copy code The code is as follows:

var message = 'Hello World';
If(message)
{
alert("Value is true");
}

When you run this example, a warning box will be displayed because the string message is automatically converted into the corresponding Boolean value (true). Because of this automatically performed Boolean conversion, it is crucial to know exactly what variables are used in flow control statements.

Number type

 This type is used to represent integers and floating-point values, and there is also a special value, NaN (Not a Number). This value is used to indicate that an operand that is supposed to return a value does not return a value (so that an error is not thrown). For example, in other programming languages, dividing any numeric value by zero results in an error that stops code execution. But in JavaScript, any value divided by 0 will return NaN, so it will not affect the execution of other code.

NaN itself has two extraordinary characteristics. First, any operation involving NaN (such as NaN/10) will return NaN, which may cause problems in multi-step calculations. Second, NaN is not equal to any value, including NaN itself. For example, the following code returns false.

Copy code The code is as follows:

alert(NaN == NaN); //false

There is an isNaN() function in JavaScript. This function accepts a parameter, which can be of any type, and the function will help us determine whether the parameter is "not a numeric value". After isNaN() receives a value, it will try to convert the value into a numeric value. Some values ​​that are not numeric are converted directly to numeric values, such as the string "10" or a Boolean value. Any value that cannot be converted to a numeric value will cause this function to return true. For example:
Copy code The code is as follows:

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

There are three functions that can convert non-numeric values ​​into numeric values: Number(), parseInt() and parseFloat(). The first function, the conversion function Number(), can be used for any data type, while the other two functions are specifically used to convert strings into numbers. These three functions will 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, just pass it in and return it
● If it is a null value, return 0
● If it is undefined, return NaN
● If it is a string, follow the following rules:

○ If the string only contains numbers, it will be converted to a decimal value, that is, "1" will become 1, "123" will become 123, and "011" will become 11 (the leading 0 is Ignore)
○ If the string contains a valid floating point format, such as "1.1", it will be converted to the corresponding floating point number (similarly, leading 0 will also be ignored)
○ If the string contains a valid hexadecimal format, such as "0xf", convert it to a decimal integer value of the same size
○ If the string is empty, convert it to 0
○ If the string contains characters other than the above format, convert it to NaN

● If it is an object, call the valueOf() method of the object, and then convert the returned value according to the previous rules. If the result of the conversion is NaN, the toString() method of the object is called, and then the returned string value is converted according to the previous rules.

Copy code The code is as follows:

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

Since the Number() function is complex and unreasonable when converting strings, the parseInt() function is more commonly used when processing integers. When the parseInt() function converts a string, it depends more on whether it conforms to the numerical pattern. It ignores leading spaces in the string until it finds the first non-space character. If the first string is not a numeric character or a negative sign, parseInt() will return NaN; that is, using parseInt() to convert an empty string will return NaN. If the first character is a numeric character, praseInt() will continue parsing the second character until all subsequent characters have been parsed or a non-numeric character is encountered. For example, "1234blue" will be converted to 1234, and "22.5" will be converted to 22, because the decimal point is not a valid numeric character.

If the first character in the string is a numeric character, parseInt() can also recognize various integer formats (i.e. decimal, octal, hexadecimal). In order to better understand the conversion rules of the parseInt() function, some examples are given below

Copy code The code is as follows:

var num1 = parseInt("1234blue"); //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"); var num6 = parseInt("70"); //70

var num7 = parseInt("10",2); //2 (parsed in binary)
var num8 = parseInt("10",8); //8 (parsed in octal)
var num9 = parseInt("10",10); //10 (parsed in decimal)
var num10 = parseInt("10",16); //16 (parsed in hexadecimal)
var num11 = parseInt("AF"); //56 (octal)
var num12 = parseInt("AF",16); var num12 = parseInt("AF",16); //175

Similar to the parseInt() function, parseFloat() also parses each character starting from the first character (position 0). And it is parsed until the end of the string, or until an invalid floating-point numeric character is encountered. That is to say, the first decimal point in the string is valid, but the second decimal point is invalid, so the string after 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 leading zeros. Since parseFloat() values ​​parse decimal values, it has no usage of specifying the base with the second parameter.

Copy code The code is as follows:

var num1 = parseFloat("1234blue"); //1234
var num2 = parseFloat("0xA"); 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 character sequence consisting of zero or more 16-bit Unicode characters, that is, a string. Strings can be represented by single quotes (') or double quotes (").

Copy code The code is as follows:

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

The length of any string can be obtained by accessing its length property
Copy code The code is as follows:

alert(str1.length); //Output 5

There are two ways to convert a value to a string. The first is to use the toString() method found on almost every value.
Copy code The code is as follows:

var age = 11;
var ageAsString = age.toString(); //String "11"
var found = true;
var foundAsString = found.toString(); //String "true"

Numeric, Boolean, object and string values ​​all have toString() method. But null and undefined values ​​do not have this method.

In most cases, there is no need to pass parameters when calling the toString() method. However, when calling the toString() method of a value, you can pass a parameter: the base of the output value.

Copy code 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)); //"a"

As you can see from this example, by specifying the base, the toString() method will change the output value. The value 10 can be converted into different numerical formats during output depending on the base.

When you don’t know whether the value to be converted is null or undefined, you can also use the conversion function String(). This function can convert any type of value into 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, return "null"
● If the value is undefined, return "undefined"

Copy code 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

An object is actually a collection of data and functions. Objects can be created by executing the new operator followed by the name of the type of object to be created. You can create a custom object by creating an instance of the Object type and adding properties and/or methods to it.

Copy code The code is as follows:

var o = new Object();

Each instance of Object has the following properties and methods:

● constructor - holds the function used to create the current object
● hasOwnProperty(propertyName) - used to check whether the given property exists in the current object instance (not in the instance's prototype). Among them, the property name (propertyName) as a parameter must be specified in the form of a string (for example: o.hasOwnProperty("name"))
● isPrototypeOf(object)——used to check whether the passed in object is the prototype of another object
● propertyIsEnumerable(propertyName) - used to check whether a given property can be enumerated using a for-in statement
● toString()——Returns the string representation of the object
● valueOf() – Returns a string, numeric or Boolean representation of the object. Usually the same as the return value of the toString() method.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template