JavaScript data types

Source: Internet
Author: User
Tags first string null null

Basic data type:

Strings: String

Numbers: Number

Boolean value: Boolean True/fasle

Special data types:

Empty object: null

Not defined: Undefined

Composite data type:

Objects: Object

Arrays: Array

One, 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 (").

such as: var name = ' Yan ';
var kemu = ' HTML5 ';
Console.log (name); Yan, the value of the output variable in the console
Console.log (KEMU); HTML5
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 = 11;
var ageasstring = age.tostring (); String "11"
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.
Second, Number type

Floating-point numbers must contain a number, a decimal point, or "E" (or "E"). Examples of floating-point numbers are: 3.1415, -3.1E12, 0.1e12, and 2E-12.

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 (10)); False (10 is a numeric value)

Alert (IsNaN ("10")); False (may be converted to a value of 10)

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 Boolean values, true and the false will be replaced separately by the 1 and the 0

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

   if it is NULL value, which 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, it is converted 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"); 11

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"); 22

var num5 = parseint ("070"); 56 (octal)

var num6 = parseint ("70"); 70

var num7 = parseint ("10", 2); 2 (by binary parsing)

var num8 = parseint ("10", 8); 8 (parsing by octal)

var num9 = parseint ("10", 10); 10 (resolution by decimal)

var NUM10 = parseint ("10", 16); 16 (parsing by hexadecimal)

var num11 = parseint ("AF"); 56 (octal)

var num12 = 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

Three, Boolean Boolean value

A Boolean value of true means "true" and False for "false." The general relational operator returns the result of a Boolean value. In addition, the value of 0,-0, the special value of NULL, NaN, undefined, and the null character ("") will be interpreted as false, and the other values will be interpreted as true.

The following code defines a Boolean object named Myboolean:

var myboolean=new Boolean ();

If the Boolean object has no initial value or its value is:

0-0 null "" False undefined NaN

Then the value of the object is false. Otherwise, its value is true, even when the argument is the string "false"!

var F1 = true, F2 = False

Console.log (F1 && F2)//False && logical operator, with

Console.log (F1 | | f2)//true | | The drain operator, or

Four null null objects and Undefined

First, the difference between null and undefined:

Executes typeof on declared but uninitialized and undeclared variables, returning "undefined".

Null represents an empty object pointer, and the typeof operation returns "Object".

Generally do not explicitly set the value of the variable to undefined, but null instead, for the variable that will save the object, you should explicitly let the variable hold a null value.

var bj;

Alert (BJ); Undefined

BJ = null;

Alert (typeof BJ); "Object"

Alert (BJ = = null); True

BJ = {};

Alert (BJ = = null); False

Null is an object, but is empty. Because it is an object, typeof null returns ' object '.
Null is a JavaScript reserved keyword.
When NULL participates in numeric operations, its value is automatically converted to 0, so the following expressions are evaluated to get the correct values:
Expression: 123 + null result value: 123
Expression: 123 *null result value: 0


Undefined is a special property of the Global Object (window) whose value is undefined. But typeof undefined returned ' undefined '.
Although undefined has a special meaning, it is really a property and a property of the Global Object (window). Take a look at the following code:

Alert (' Undefined ' in window); Output: True

var anobj = {};

Alert (' undefined ' in anobj); Output: false

As you can see, undefined is a property of the Window object, but it is not a property of the Anobj object.
Note: Although undefined is a special-meaning property, it is not a reserved keyword for JavaScript.
When undefined participates in any numerical calculation, the result must be Nan.
To say the same, Nan is another special property of the Global Object (window), and so is infinity. These special properties are not javascript reserved keywords!

V. Object objects

The most basic data type in JavaScript is the object. The object in JavaScript is actually a set of unordered attributes, which are also named-value pairs.

Except for strings, numbers, true,false,null, or undefined, all other values are objects inside JavaScript.

The object is a reference type, and if the variable x represents an object, when the Var y =x is executed, and after the statement, Y and X are actually pointing to the same object. So, when you change the value of an object by Y, the change is also reflected on the X.

How to create an object:


1. Literal notation:

var book = {}; Create an object with no attributes
var book = {
Name: "The Definitive Guide";
"Main title": "JavaScript"; Enclose the attribute name in quotation marks when there is a space in the middle of the property name, or "-".
Author: The property of the {//object can also be an object
FirstName: "Rex";
LastName: "Mai";
}
};

2. Use the New keyword:

var o = new Object (); Creates an empty object that has the same effect as {}.
var a = new Array (); Creates an empty array with the effect equal to [].
var d = new Date (); Creates an object that represents the current time
var r = new RegExp ("JS"); Create a regular Expression object

3. Using Object.create (), this is the newly added method of ECMAScript5, which takes a parameter-object prototype.

var O1 = object.create ({x:1, y:2});
var O2 = object.create (Object.prototype); The result is the same as {} or New Object ()
You can pass null to the method, and the result will be an empty object that does not inherit any properties and methods

Gets the value of the object:

Pass the. or [] operator.

Book.title;
book["title"];
var propertyname = "title";
Book[propertyname];
If the properties of an object are fixed, the two methods do not have much difference. But because JavaScript is a loosely typed language, you can add any number of attributes to an object during the program's run. When you use the. operator to access the object properties, the. After name is actually just an identifier, so you must enter the identifier completely before you can access it.
object, value in {Name:value}, key pair value, property name: property value
The corresponding property value can be found according to its property name
Console.log (Info)//Object {name: "Yan", Kemu: "HTML5", Age: "3"}
Console.log (info.name)//Yan

Six, arrays (array)

The array of ECMAScript is quite different from the array in other languages. Although the array in ECMAScript is also a sequential list, it can hold any type of data for each of your entries. The size of the ECMAScript array can be dynamically adjusted.

There are two basic ways to create an array

The first is the use of Array constructor, as follows:

Copy the code code as follows:


var colors = new Array ();


If you know the number of items the array is to be saved, you can also pass parameters to the constructor, which automatically becomes the value of the length property, as follows:


var colors = new Array (20);


You can also pass the items that should be included in the array to the array constructor, as shown in the following code:


var colors = new Array ("Red", "blue");

The second type of use Array constructor, you can also omit the New operator, as shown below:

var colors = Array (20);


The second way to create an array is by using the array literal notation. The array literal is represented by a pair of square brackets that contain array items, separated by commas between multiple array items, as follows:

Copy the code code as follows:


var color = ["Red", "Blue"];
var names = [];
var values = [up,]//ie8 and previous 3 items, other 2 items, not recommended


As with objects, the constructor of the array is not called when using numeric literal notation.

When reading and setting the value of an array, use square brackets and provide a 0-based numeric index of the corresponding value, as follows:

Copy the code code as follows:

var colors = ["Red", "Blue"]; Defining arrays
Alert (colors[0]);//red
COLORS[1] = "BLACK"//Modify Item 2nd
COLORS[2] = "Brown"//New 3rd

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.