Data type of JS

Source: Internet
Author: User
Tags hasownproperty

The following data types are defined in javascript:
    • Strings (String)
    • Numbers (number)
    • Boolean (Boolean)
    • Arrays (Array)
    • Objects (object)
    • Null (NULL)
    • Undefined (Undefined)
1. String

A string is any text enclosed in single quotation marks ' or double quotation marks:

var carname= "Volvo XC60"; var carname= ' Volvo XC60 ';

If it is also a character, it can be "" enclosed:

var answer= "It ' s Alright";

If it " is also a character, it can be ‘‘ enclosed:

var answer= ' He is called ' Johnny ';

What if the inside of a string contains and contains both " ? Can be identified by an escape character \ , such as:

' I\ ' m \ ' ok\ '! ';

An escape character \ can escape many characters, such as a \n newline, a \t tab, and the character \ itself, so \\ the character that is represented is \ .

Multi-line string

Because multiline strings are more \n cumbersome to write, the newest ES6 standard adds a multiline string representation, using the anti-quote ' ... ' means:

' This is a multi-line string ';

Template string

To concatenate multiple strings, you can connect them with a + number:

var name = ' Xiaoming '; var age = 20;var message = ' Hello, ' + name + ', you are this year ' + Ages + ' old! '; alert (message);

If there are many variables that need to be connected, + it is more troublesome to use the number. ES6 adds a template string that represents the same method as the multiline string above, but it automatically replaces the variables in the string:

var name = ' Xiaoming '; var age = 20;var message = ' Hello, ${name}, you ${age} year old! '; alert (message);

Manipulating strings

Length

Get string length

var s = ' Hello, world! '; S.length; 13

To get a character at a specified position in a string, use an array-like subscript operation with the index number starting at 0:

var s = ' Hello, world! '; S[0]; ' H ' s[6]; "S[7"; ' W ' s[12]; ‘!‘ S[13]; Undefined out of range index will not error, but return undefined

It is important to note that the string is immutable, and there is no error if you assign a value to an index of the string, but it does not have any effect:

var s = ' Test '; s[0] = ' X '; alert (s); S is still ' Test '

JavaScript provides some common methods for strings, note that calling these methods does not alter the contents of the original string, but instead returns a new string:

toUpperCase

toUpperCase () turns a string all uppercase:

var s = ' Hello '; s.touppercase (); Return ' HELLO '

toLowerCase

toLowerCase()Turn a string all lowercase:

var s = ' Hello '; var lower = S.tolowercase (); Return ' Hello ' and assign value to variable lowerlower; ' Hello '

IndexOf

IndexOf () searches for the location where the specified string appears:

var s = ' Hello, world '; S.indexof (' World '); Return to 7s.indexof (' World '); The specified substring was not found, returned-1

LastIndexOf

LastIndexOf () searches for the specified character from the tail of the string to the head:

var s = ' Hello '; S.lastindexof (' l ');   Returns 3

Substr

SUBSTR () intercepts the string:

var s = ' Hello '; s.substr; Return ' El '//intercept string of length 2 starting at index 1

Substring

substring()Returns the substring of the specified index interval:

var s = ' Hello, world ' s.substring (0, 5); Starting from index 0 to 5 (excluding 5), return ' Hello ' s.substring (7); Starting at index 7 to the end, return ' world '

Trim

Trim () to remove whitespace on both sides of the string:

var s = ' Hello '; S.trim ();   Return ' Hello '

CharAt

CharAt () Gets the specified position character:

var s = ' Hello '; S.charat (1);   Return ' E '

Match and search

Match () returns an array of matching strings, or null if no match

Search () returns the first character position index of the matched string:

var str1= "Welcome to the world's World js!"; var str2=str1.match ("World"), Var str3=str1.search ("World"), alert (str2[0]);  The result is "world" alert (STR3);     Result is 15

Slice

Slice (), slicing the string:

var str1= "abcdefgh"; var str2=str1.slice (2,4);   The result is "CD", starting at index 2, intercepting to index 4, not including index 4var str3=str1.slice (4);     The result is "EFGH", starting at index 4, and intercepting to the end of the string Var str4=str1.slice (2,-1);  The result is "CDEFG", starting at index 2, intercepting the end of the string, not including the trailing character Var str5=str1.slice ( -3,-1); The result is "FG", starting at index 3, intercepting the end of the string to index-1, with no trailing character

Replace

Replace (), replacement string:

var s = ' hello,jack '; S.replace (' Jack ', ' Michael ');   Back to ' Hello,michael '

Split

Split (), split string:

var str1= "One, two, three, four, five, six, day"; var strarray=str1.split (",");   return array: ["One", "two", "three", "four", "Five", "VI", "Day")
2. Numbers (number)

JavaScript does not distinguish between integers and floating-point numbers, and is uniformly represented by number, and the following are valid number types:

123; Integer 1230.456; floating point 0.4561.2345e3; Scientific notation represents 1.2345x1000, equivalent to 1234.5-99; Negative number Nan; Nan represents not a number, and Nan is used to denote infinity when the result cannot be computed; Infinity is infinitely large, and is represented as infinity when the value exceeds the maximum value that JavaScript can represent.

Because the computer uses binary, it is sometimes convenient to use hexadecimal notation for integers, hexadecimal is represented by 0x prefixes and 0-9,a-f, for example:,, and 0xff00 0xa5b4c3d2 so on, and they are exactly the same as decimal values.

2 binary: 1111 0011 1101 0100   <-----> 16:0xf3d4 <-----> 10 binary: 624202 binary: 1 111 001 111 010 <-----> 8 in System: 0171724

3. Boolean value (Boolean)

Boolean and Boolean algebra are fully consistent, a Boolean value of only true false two kinds of values, either, true or false , can be directly used, to true represent the false boolean value, the actual operation of the true=1,false= 0, can also be calculated by Boolean operation:

True This is a true value of false; This is a false value of 2 > 1; This is a true value of 2 >= 3; This is a false value

4. Arrays (array) a. Defining arrays

An array is a set of sequentially arranged collections, each of which is called an element. An array of JavaScript can include any data type. For example:

[1, 2, 3.14, ' Hello ', NULL, true];

The above array consists of 6 elements. Arrays [] are represented by , separate elements.

Another way to create an array is through a Array() function:

New Array (1, 2, 3); Array created [1, 2, 3]

However, for the sake of readability of the code, it is strongly recommended to use it directly [] .

The elements of an array can be accessed through an index. Notice that the starting value of the index is 0 :

var arr = [1, 2, 3.14, ' Hello ', NULL, true];arr[0]; Returns an element with an index of 0, which is 1arr[5]; Returns an element with an index of 5, which is truearr[6]; Index is out of range, return undefined
B. Properties and methods of an array

To get Array the length, directly access the length properties:

var arr = [1, 2, 3.14, ' Hello ', null, true];arr.length; 6

Please note that Array length assigning a new value directly to the given will result in a Array change in size:

var arr = [1, 2, 3];arr.length; 3arr.length = 6;arr; Arr becomes [1, 2, 3, undefined, undefined, undefined]arr.length = 2;arr; Arr becomes [1, 2]

An array can be indexed to modify the corresponding element to a new value, so Array assigning a value to an index modifies this directly Array :

var arr = [' A ', ' B ', ' C '];arr[1] = 99;arr; Arr now changes to [' A ', ' A ', ' C ']

Note that if an index is assigned a value, the index is out of range, which can also cause Array a change in size:

var arr = [1, 2, 3];arr[5] = ' x '; arr; Arr becomes [1, 2, 3, Undefined, undefined, ' X ']

Most other programming languages do not allow direct changes to the size of the array, and an error occurs when accessing the index out of bounds. However, JavaScript Array does not have any errors. When writing code, it is not recommended to directly modify Array the size of the index to ensure that the index does not cross.

IndexOf

Similar to string, Array you can also indexOf() search for the position of a specified element by:

var arr = [Ten, 10, ' + ', ' xyz '];arr.indexof. The index of Element 10 is 0arr.indexof (20); The index of Element 20 is 1arr.indexof (30); Element 30 is not found and returns -1arr.indexof (' 30 '); The index of element ' 30 ' is 2

Slice

Slice () is the version of the corresponding string substring() , which intercepts Array the part of the element and then returns a new one Array :

var arr = [' A ', ' B ', ' C ', ' D ', ' E ', ' F ', ' G '];arr.slice (0, 3); Starting at index 0, ending with index 3, but excluding index 3: [' A ', ' B ', ' C ']arr.slice (3); Starting from index 3 to end: [' D ', ' E ', ' F ', ' G ']

Notice that slice() the start and end parameters include the starting index, not the ending index.

If you don't slice() pass any arguments, it intercepts all the elements from the beginning to the end. With this, we can easily copy one Array :

var arr = [' A ', ' B ', ' C ', ' D ', ' E ', ' F ', ' G '];var acopy = Arr.slice (); acopy; [' A ', ' B ', ' C ', ' D ', ' E ', ' F ', ' G ']acopy = = = Arr; False

Push and pop

Push () Array adds a number of elements to the end, then the pop() Array last element is removed:

var arr = [1, 2];arr.push (' A ', ' B '); Returns the new length of the array: 4arr; [1, 2, ' A ', ' B ']arr.pop (); Pop () returns ' B ' arr; [1, 2, ' A ']arr.pop (); Arr.pop (); Arr.pop (); Consecutive POPs 3 times arr; []arr.pop (); The empty array continues to pop without error, but returns Undefinedarr; // []

Unshift and Shift

If you want to Array add several elements to the head, using the unshift() method, the shift() Array first element of the method is deleted:

var arr = [1, 2];arr.unshift (' A ', ' B '); Returns the new length of the array: 4arr; [' A ', ' B ', 1, 2]arr.shift (); ' A ' arr; [' B ', 1, 2]arr.shift (); Arr.shift (); Arr.shift (); Continuous shift 3 times arr; []arr.shift (); An empty array continues shift without error, but returns Undefinedarr; // []

Sort

Sort () sorts the current, and Array it directly modifies Array the current element position, which is ordered in the default order when it is called directly:

var arr = [' B ', ' C ', ' A '];arr.sort (); arr; [' A ', ' B ', ' C ']

When you sort a numeric element, there is a case in which the numeric size is not true:

Arr=[1,5,2,100];arr.sort (); Console.log (arr)    //Sort result: [1, 100, 2, 5]//This is because the default is to sort by the ASCII code of the characters, the first character is the same, then the 2nd bit is compared. It is not sorted according to the true size of the numbers.

Workaround:

Arr=[1,5,2,100];function Intsort (A, b) {    if (a>b) {        return 1;    }    else if (a<b) {        return-1;    }    else {        return 0    }}arr.sort (intsort); Console.log (arr)    //Sort result: [1, 2, 5, 100]//intsort function can also be written as follows// function Intsort (A, B) {//    return a-b;//}

Reverse

Reverse () Reverses the entire Array element:

var arr = [' One ', ' both ', ' three '];arr.reverse (); Arr [' Three ', ' one ', ' one ']

Splice

The splice () method is a modified Array "universal method" that deletes several elements starting at the specified index, and then adds several elements from that location:

var arr = [' Microsoft ', ' Apple ', ' Yahoo ', ' AOL ', ' Excite ', ' Oracle '];//remove 3 elements from index 2, and then add two elements: Arr.splice (2, 3, ' Google ', ' Facebook '); Returns the deleted element [' Yahoo ', ' AOL ', ' Excite ']arr; [' Microsoft ', ' Apple ', ' Google ', ' Facebook ', ' Oracle ']//only deleted, not added: Arr.splice (2, 2); [' Google ', ' Facebook ']arr; [' Microsoft ', ' Apple ', ' Oracle ']//only add, do not delete: Arr.splice (2, 0, ' Google ', ' Facebook '); return [], because no element was removed from arr; [' Microsoft ', ' Apple ', ' Google ', ' Facebook ', ' Oracle ']

Concat

The Concat () method connects the current Array and the other and Array returns a new one Array :

var arr = [' A ', ' B ', ' C '];var added = Arr.concat ([1, 2, 3]); added; [' A ', ' B ', ' C ', 1, 2, 3]arr; [' A ', ' B ', ' C ']

note that the concat() method does not modify the current Array , but instead returns a new one Array .

In fact, the concat() method can receive any element and Array automatically Array disassemble it and add it all to the new one Array :

var arr = [' A ', ' B ', ' C '];arr.concat (1, 2, [3, 4]); [' A ', ' B ', ' C ', 1, 2, 3, 4]

Join

The join () method is a very useful way to Array concatenate each current element with a specified string, and then return the concatenated string:

var arr = [' A ', ' B ', ' C ', 1, 2, 3];arr.join ('-'); ' A-b-c-1-2-3 '

If Array the element is not a string, it is automatically converted to a string and then concatenated.

5. Objects (object)

A JavaScript object is a set of unordered collections of key-value, for example:

var person = {    name: ' Bob ',    age:20,    Tags: [' js ', ' web ', ' mobile '], City    : ' Beijing ',    hascar:true,< C5/>zipcode:null};

The key of a JavaScript object is a string type, and the value can be any data type. All of the above person objects define a total of 6 key-value pairs, each of which is also called an object's properties, for example, the property is person name ‘Bob‘ zipcode null .

To get the properties of an object, we use 对象变量.属性名 the following method:

Person.name; ' Bob ' Person.zipcode; Null

The Access property is . done through the operator, but this requires that the property name must be a valid variable name. If the property name contains special characters, it must be ‘‘ enclosed:

var xiaohong = {    name: ' Little Red ',    ' middle-school ': ' Middle School '};

Xiaohong Property name middle-school is not a valid variable, it needs to be ‘‘ enclosed. Accessing this property also fails to use the . operator and must be accessed by [‘xxx‘] :

xiaohong[' Middle-school ']; ' Middle School ' xiaohong[' name ']; ' Little Red ' xiaohong.name; ' Little Red '

can also be used xiaohong[‘name‘] to access xiaohong the name properties, but xiaohong.name the wording is more concise. When we write JavaScript code, the property name tries to use the standard variable name as much as possible, so that a property can be accessed directly through object.prop the form.

Virtually all the properties of a JavaScript object are strings, but the value of the property can be any data type.

What does it return if a property that does not exist is accessed? JavaScript specifies that access to non-existent properties is not an error, but rather returns undefined :

var xiaoming = {    name: ' Xiaoming '};xiaoming.age;//undefined

Because JavaScript objects are dynamic types, you are free to add or remove attributes to an object:

var xiaoming = {    name: ' Xiaoming '};xiaoming.age;//undefinedxiaoming.age = 18;//Add an Age attribute xiaoming.age;//18delete Xiaomi Ng.age; Delete the age attribute xiaoming.age; Undefineddelete xiaoming[' name ']; Remove the name attribute Xiaoming.name; Undefineddelete Xiaoming.school; Deleting a non-existent school property will not error

If we want to detect if we xiaoming have a property, we can use the in operator:

var xiaoming = {    name: ' Xiaoming ',    birth:1990,    School: ' Middle School ',    height:1.70,    Weight:65,
   score:null}; ' Name ' in Xiaoming; True ' grade ' in xiaoming; False

Be careful, however, that if in a property is judged to exist, this property is not necessarily xiaoming the case, it may be xiaoming inherited:

' ToString ' in xiaoming; True

Because toString it is defined in an object object, and all objects end up pointing at the prototype chain object , xiaoming They also have toString properties.

To determine whether a property is xiaoming owned by itself, but not inherited, you can use the hasOwnProperty() method:

var xiaoming = {    name: ' Xiaoming '};xiaoming.hasownproperty (' name ');//Truexiaoming.hasownproperty (' toString ');//False
6. Null & undefined type

Undefined type

The Undefined type has only one value, which is Undefined. When the declared variable is not initialized, the default value of the variable is undefined.

When the function has no definite return value, the returned value is also "undefined";

Null type

Another type with only one value is null, and it has only one private value, NULL, which is its literal. The value undefined is actually derived from the value null, so ECMAScript defines them as equal.

Although the two values are equal, they have different meanings. Undefined is a value that is assigned to a variable when it is declared but not initialized, and null is used to represent an object that does not already exist (this is briefly described when discussing the typeof operator). If the function or method is to return an object, the object returned is usually null when it is not found.

Resources:

1. http://www.w3cschool.cn/javascript/js-datatypes.html

2. Http://www.liaoxuefeng.com/wiki/001434446689867b27157e896e74d51a89c25cc8b43bdb3000/ 001434499190108eec0bdf14e704a09935cd112e501e31a000

3. http://www.cnblogs.com/yuanchenqi/articles/6893904.html

Data type of JS

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.