JavaScript basic syntax + data type

Source: Internet
Author: User
Tags access properties array sort delete key ming

We all put JavaScript code in 1.JavaScript code written in <script>...</script> internal
2. Put the JavaScript code in a separate. js file, and then in the HTML by <script src= "..." ></script> introduce this file
<script type= "Text/javascript" > this is not necessary because the default type is JavaScript, so you do not have to explicitly specify the type as JavaScript.

However, due to browser security restrictions, the address beginning with file://cannot execute JavaScript code such as networking,
Eventually, you need to set up a Web server and then execute all JavaScript code with an address starting with http://.

Avascript syntax is similar to the Java language, with each statement ending with a statement block with {...}. However, JavaScript does not impose a requirement at the end of each statement, and the engine responsible for executing JavaScript code in the browser is automatically added at the end of each statement;

Single-line comment//Multiline comment/*...*/

Underlying data type
Number:javascript does not distinguish between integers and floating-point numbers, and a uniform number represents NaN;//Nan means not a number, which is represented by Nan when the result cannot be evaluatedInfinity;//Infinity is infinitely large, and is represented as infinity when the value exceeds the maximum value that JavaScript can represent.Hex with 0x prefix and 0-9,a-F means that the special number of Nan is not equal to all other values, including its own only way to Judge Nan is through the isNaN () function-----IsNaN (NaN);//trueThe string is in single quotation marks‘or double quotation marks around any text Boolean value only true, false two values && operations are associated with operations | | Operation is OR operation! operation is a non-operation in fact, JavaScript allows you to make comparisons of arbitrary data types with special attention to equality operator = =. JavaScript is designed with two comparison operators: the first is = = comparison, which automatically converts data types and compares them, often with very bizarre results, and the second is the = = = comparison, which does not automatically convert data types, if the data type is inconsistent, returns false, if consistent, and then compare. It is recommended to always stick to the = = = comparison. /3 = = = (1-2/3); False this is not a design flaw for JavaScript. Floating-point numbers generate errors during operation, and Null represents an "empty" value, and 0 and an empty string"Different, 0 is a number, '"represents a string of length 0, and null means "null". Undefined indicates that the value is undefined, and the difference between the two is insignificant. In most cases, we should all use NULL. Undefined is useful only when judging whether a function parameter is passed or not. Undefined looks like a subclass of NULL??? The underlying data type variable is represented by a variable name in JavaScript, and the variable name is a combination of uppercase and lowercase English, numeric, $, and _, and cannot begin with a number. In JavaScript, use equal sign = To assign a value to a variable. Arbitrary data types can be assigned to variables, the same variable can be repeatedly assigned, and can be different types of variables, but note that only with the Var declaration if a variable is not used by the Var declaration, then the variable is automatically declared as a global variable without var declaration of the variable will be treated as a global variable, To avoid this flaw, all JavaScript code should use the strict mode. The escape character \ can escape many characters, such as \ n for newline, \ t for tabs, and the character \ itself to be escaped, so \ \ is the character that \ \. ASCII characters can be \x# #形式的十六进制表示还可以用 \u### #表示一个Unicode字符最新的ES6标准新增了一种多行字符串的表示方法, using the anti-quote ' ... ' to concatenate multiple strings, you can use the + Number of connections if there are many variables need to connect, with the + number is more troublesome. ES6 adds a template string that represents the same method as the multiline string above, but it automatically replaces the variable in the string var name =' Xiao Ming 'var age = 20;var message = ' Hello, ${name}, you ${age} year old! '; alert (message);
base language, underlying data typeString

A JavaScript string is represented by a character enclosed in "or".
What if the inside of a string contains both ' and contains '? You can use the escape character \ To identify, for example: ' I\ ' m \ ' ok\ '! ';

The escape character \ can escape many characters, such as \ n for newline, \ t for tabs, and the character \ itself to be escaped, so \ \ is the character that \ \.

ASCII characters can be #形式的十六进制表示 in \x#, for example: ' \x41 '; Exactly the same as ' A '
can also use \u### #表示一个Unicode字符: ' \u4e2d\u6587 '; Exactly the same as ' Chinese '

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

You can concatenate multiple strings with the + sign
If there are many variables that need to be connected, using the + sign is more troublesome. 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 = ' Xiao Ming '; var age =; var message = ' Hello, ${name}, you ${age} year old! '; alert (message);
Template String Example
// get the length of a string as in JS, you can index a string substring () returns the substring of the specified index interval // slices are used substring 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 there is no effect. JavaScript provides some common methods for strings, noting that invoking these methods does not alter the contents of the original string itself. Instead, it returns a new string toUpperCase () turns a string all uppercase toLowerCase () turns a string all lowercase indexof () The JavaScript code that will search for the location where the specified string appears will be written in strict mode. (Force var when declaring a local variable)
Manipulating StringsArray

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.
Another way to create an array is through the array () function: New Array (1, 2, 3);

The array of JavaScript can contain any data type, and each element is accessed through an index.
To get the length of the array, direct access Length property
Note that assigning a new value directly to the length of the array will result in a change in the size of the array

var arr = [1, 2, 3//  3arr.length = 6//  arr becomes [1, 2, 3, Undefined, Undefined, undefined]arr.length = 2//  arr becomes [1, 2]
View Code

An array can be indexed to modify the corresponding element to a new value, so assigning a value to the index of an array modifies the array directly.
Note that if an index is assigned a value, the index is more than the range, which also causes the array size to change

like string, array can also search for the location of a specified element by indexof () JS can be indexed, but the slice needs to use slice () slice () is the substring () version of the corresponding string, It intercepts some elements of an array, and then returns a new Arraypush () adds several elements to the end of the array pop () removes the last element of the array unshift () adds several elements to the head of the array shift () Remove the first element of the array sort () to sort the current array, which directly modifies the position of the elements of the current array, and, when called directly, sorts reverse () in the default order () to reverse the elements of the entire array concat () Method joins the current array with another array and returns a new Arrayconcat () method that can receive any element and array, and automatically take the array apart and add it all to the new array join () method is a very useful method, It connects each element of the current array with the specified string, and then returns the concatenated string splice () method is a "universal method" to modify the array, which can remove several elements from the specified index and then add several elements from that locationvararr = [' Microsoft ', ' Apple ', ' Yahoo ', ' AOL ', ' Excite ', ' Oracle '];//Delete the 3 elements starting at index 2, and then add the two elements:Arr.splice (2, 3, ' Google ', ' Facebook ');//return deleted elements [' Yahoo ', ' AOL ', ' Excite ']Arr//[' Microsoft ', ' Apple ', ' Google ', ' Facebook ', ' Oracle ']//Delete only, do not add:Arr.splice (2, 2);//[' Google ', ' Facebook ']Arr//[' Microsoft ', ' Apple ', ' Oracle ']//add only, do not delete:Arr.splice (2, 0, ' Google ', ' Facebook ');//return [] because no elements were removedArr//[' Microsoft ', ' Apple ', ' Google ', ' Facebook ', ' Oracle ']
Array ManipulationObject

An Avascript object is an unordered collection data type that consists of several key-value pairs. ------is a python dictionary.
The key of a JavaScript object is a string type, and the value can be any data type.

Note that the last key value pair does not need to be added at the end, if added, some browsers (such as the lower version of IE) will error.

Access properties are 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 in
Xiaohong Property name Middle-school is not a valid variable, it needs to be enclosed. Access to this property is also not possible with the. operator, which must be accessed using [' xxx ']

Access to non-existent attributes does not error, but returns undefined

If we want to detect if Xiaoming has a property, you can use the in operator: if in determines that an attribute exists, this property is not necessarily xiaoming, it may be xiaoming inherited

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

Conditional judgment

if () {...} or else {...}

If you want to judge the condition more carefully, you can use multiple if...else ... The combination

var age = 3; if (age >=) {alert (' adult 'elseif (>= 6) {alert (' teenager '   Else  {alert (' Kid ');}
Example

Please note that if...else ... The execution characteristic of the statement is two select one, in multiple if...else ... Statement, if a condition is true, subsequent judgments are no longer continued.

Cycle

for (I=1; i<=10000; i++) {x = x + i;}
I=1 This is the initial condition, the variable i is set to 1;
i<=10000 This is the judgment condition, when satisfies the circulation, does not satisfy on exits the circulation;
i++ This is the increment condition after each loop, because the variable i is incremented by 1 after each cycle, it will eventually exit the loop after several cycles without satisfying the judging condition i<=10000.

The 3 conditions of the For loop can be omitted, and if there are no criteria for exiting the loop, the break statement must be used to exit the loop, or the dead loop

var x = 0;  for // will be infinite loop down if (x > +) {break//  exit loop  + + via if judgment;}
Example

A variant of the For loop is a for ... in loop, which loops through all the properties of an object in turn:

var o =' Jack' Beijing '};  for (varin//  ' name ', ' age ', ' City '}
Example

While Loop has only one judgment condition, the condition satisfies, then loops continuously, the condition does not satisfy the exit loop.

var x = 0; var n =;  while (n > 0= x += n-2//  2500
Example

Do {...} while () loop, the only difference between it and the while loop is that the condition is not judged at the beginning of each loop, but rather when each loop is completed

var n = 0;  Do  = n + 1 while (n <//  
Example

Use the do {...} while () loop to be careful, the loop is performed at least 1 times, and the for and while loops may not execute at once.

Map & Set

Map and set are new data types for the ES6 standard, depending on the browser's support, decide whether to use it.

the default object representation of JavaScript {} can be treated as a map or dictionary data structure in another language, a set of key-value pairs. But the JavaScript object has a small problem, which is that the key must be a string. But actually number or other data type as a key is also very reasonable. To solve this problem, the latest ES6 specification introduces a new data type map. Map is the structure of a set of key-value pairs, with extremely fast search speed write a map with JavaScript as followsvarm =NewMap ([' Michael ', ' up], [' Bob ', []], [' Tracy ', 85]]); M.get (' Michael ');// theinitializing a map requires a two-dimensional array, or directly initializing an empty map. Map has the following methods:varm =NewMap ();//Empty MapM.set (' Adam ', 67);//Add a new Key-valueM.set (' Bob ', 59); M.has (' Adam ');//is there a key ' Adam ': trueM.get (' Adam ');// theM.Delete(' Adam ');//Delete key ' Adam 'M.get (' Adam ');//undefinedbecause a key can only correspond to a value, so, multiple times a key into value, the following value will flush the previous value out to create a set, you need to provide an array as input, or create an empty set directly:varS1 =NewSet ();//Empty SetvarS2 =NewSet ([1, 2, 3]);//including 1, 2, 3duplicate elements are automatically filtered in set by the Add (key) method can be added to the set, can be repeatedly added, but no effect through the Delete (key) method can delete the element
description and examples

JavaScript basic syntax + data type

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.