JS Basic syntax

Source: Internet
Author: User

Connection: http://ife.baidu.com/note/detail/id/1398

JS Basic Grammar Summary
1. Classification
ECMAScript JS Basic grammar and standard
DOM Document Object Model documents
BOM Browser Object Model Explorer
2. Annotation method
Style/ /
Body <!----! >
Script//
/ /
/**

    *   js说明文档注释    */

3. Simple instruction
Alert (""); Prompt box;
Confirm (""); Confirm box, the response returns TRUE or false when clicked;
Prompt (); pops up an input box;
document.write ("");
Console.log (""); Print the appropriate information on the console;
Console.dir (""); Print out all information about the object in the console;
4. Variable naming
Number (0-9), Letter (A-z,a-z), underscore (_);
Tips: Avoid words and keywords;
5, Nan and isNaN
IsNaN, or True if number is not a digit;
Number, when converted to a numeric type, returns Nan if number is not a digit;
6. Escape character

R Enter
N Spaces
T indent
Back slash
7, logical short circuit, logical interrupt
true | | 6; Logic or short circuit, the left side is ture return right value;
6 && true; Logic and short, left false return right value;
8. Priority level

* / %+   -&&||?

Tips: top-down priorities are getting higher
9 conversion (type)
parseint ("12a3"); Convert to digital, try to strong turn;
Parsefloat ("123.123");

Data.tostring ();
String (data);

tips:变量声明未赋值,其值为undefined;    对象为空,其值为null;

10, three-dimensional expression
eg:a>b?a=1:a=2;

Format:
Judging the conditions? True when the action is performed: False when the operation is performed;
11. Arrays Array
(1), definition Law
constructor function:
var arr = new Array ("123", "abc", "XXX");
Literal:
var arr = ["123", "646", "abc"];
Array Length:
var arr = new Array (6);(array length is 6);
(2), assign value
Arr[0]=1;
12. Formal parameters and arguments
Functions Funca (a,b,c) {} When defining a function, where a, B, and C are formal parameters;
When calling a function, Funca (1, 2, 3) is the argument;

There is a arguments object inside the tips:function, which holds the arguments of all the functions passed into the function;
13. Function functions
(1), function naming
1, can use characters, numbers, underscores, $;
2, can not start with a number;
3, can not use keywords and reserved words;
4, case-sensitive;

5、  建议要有意义 --  动词+名字结构;6、  驼峰命名法;7、  函数名不能重名,后面写的重名函数会把前面写的函数给覆盖掉;

(2), return value of function
return value:
When the function is finished, the result is a function return value
Any function has a return value

1. The return value of the function is undefined when there is no return written inside the function;
2. When there is a return inside the function, but the return is not followed by any content or data,
The return value of the function is undefined, and the code after return does not execute;
3, when the return followed by the content or data, the return value of the function is the following content or data;

(3), four forms of the function:
1, no parameters, no return;
Usually lies in encapsulating a process;
2, no parameters, there is return;
Typically used for internal encapsulation referencing other functions (closures, callbacks);
3, there are parameters, no return;
Encapsulation that is typically used to perform operations;
4, has the parameter, has the return;
Common form;

(4), anonymous function
The Name property value of the anonymous function is anonymous;
function is only used once, that is, waste;

eg:    setTimeout(function(){        console.log(this.name); },1000);tips:在1秒后在控制台打印出本函数的名称;

(5), callback function
In one function, another function is passed into the function as a parameter, and the other function is the callback function;
eg
function Atack (callback) {
return callback;
}
Tips: When calling this function, specify which function callback is.
Atack (func);

(6), short circuit operation
Role: To prevent the data passed into the function is not enough, resulting in the inability to run;
eg
function GetResult (A,B,FN) {
fn && fn ();
} (usually using a short circuit with logic to decide whether to execute the callback function;)

    function getResult_2(a,b){        a || 0; }(通常用逻辑或的短路来防止实参不足的情况,强行赋值;)

(7), self-executing function
(function Func2 () {

})()tips:在函数定义的结束最后写入一个(),该函数定义完成后直接被调用执行;

(8), recursion
At the end of the function execution, call itself again;

tips:递归是一种非常耗资源的做法,通常为了简化运算,还会结合缓存进行;并且注意,递归必须要有结束判断条件(if),否则该函数被调用后就是死循环;

14. Data type
(1), simple data type
String, Number, Boolean

(2), complex data types
String, number, Boolean, Array, Math, Date, Obeject, function, REGEXP (regular expression)

(3), empty data type

Null  ---→Null的数据类型会返回一个Object* undifinedtips:用typeof可以进行判断数据类型;tips:定义的简单数据类型变量,其数据保存在变量中;    而复杂数据类型,其变量保存的是数据所在的内存地址;

15. Built-in objects
Array, Date, Math, String;
16. Math Object (Math)
Rounding up Math.ceil (number);
Rounding down Math.floor (number);

Rounding Math.Round (number);

Find the maximum value between multiple numbers Math.max ();
Find the minimum value between multiple numbers math.min ();

The Y-Power Math.pow (x, y) is obtained.

The sine value Math.sin (x) is obtained.
Example
To find the sine of an angle, the x must be a value of the amount of radians
Conversion formula for angles and radians:
Radian = Angle 2 math.pi/360;

    Math.sin(30*2*Math.PI/360)

Math.Abs (x); Get the absolute value of a number
17, (array) Array object
(1), Arr1.concat (ARR2);
Array concatenation, the result is the arr2 stitching to the arr1 of the last;

(2), Arr.join ();
Array string output, in parentheses can specify the symbol of the element connection;
eg
Arr=["A", "B", "C", "D"];
Console.log (Arr.join ("|")); (The result is "a|b|c|d")

(3), Arr.pop ();
The last element of the array is cut, and the return value is the element;

(4), Arr.slice (Start,end)
Gets, gets the specified fragment of the array, start must have, if the argument is negative, start from the end of the selection;
The return value is a new array consisting of the fragment;

(5), Arr.push
Added to add a new element to the end of the array, the parameters can be multiple;
The return value is the new length of the array;

(6), Arr.splice
1, to add elements to the index specified in the array;
Arr.splice (2, 0, "William", "asdfasdf");
At the beginning of the 2nd element, the number of elements to delete (can be 0, 0 to the end),
Adding elements as "William", "ASDFASDF";

    2、用于替换数组中的元素;        arr.splice(2,1,"William");              3、用于删除数组中的元素; arr.splice(2,2);

(7), arr.indexof (element);
Finds, finds an element in an array, returns a value of index, if no element returns-1;

(8), arr.sort (function);
Sort, functions as a function;
eg
function Sortnumber (A, b) {
return a-B;
}
Arr.sort (Sortnumber);(order from small to large)

tips:如果a-b改成b-a,那么执行的操作为从大到小;tips:字符串对象(String)的方法与Array的方法类似;

18, (date) Date Object
Date.gettime ()
Date.getmilliseconds ()
Date.getseconds ()
Date.getminutes ()
Date.gethours ()
Date.getday ()
Date.getdate ()
Date.getmonth ()
Date.getfullyear ()

Tips: Many, check documents
19, (String) object
CharAt (Index)
Str[index] Gets the character of the string at the specified position

Concat () Stitching strings

Slice (start,end)/
SUBSTRING (start,end) intercepts the characters from start, end,
Returns a new string, starting with the last character, if start is a negative number;

SUBSTR (start,length) intercepts characters from start, length, and gets a new string

IndexOf (char) Gets the position of the specified character in the string for the first time
LastIndexOf (char) Gets the position of the last occurrence of the specified character in the string

Trim () to remove whitespace before and after a string

toUpperCase ()
Convert toLocaleUpperCase () to uppercase

toLowerCase ()

Convert tolocalelowercawse () to lowercase

Replace () Replacement character
Split () split string array
20. Custom Objects
Object: A collection of unordered attributes;
Feature: Attribute (key);
Behavior: Method (value);

JS is an object-based weakly typed language;

Inheritance: A class-based feature that subclasses can get from a parent class;

Factory mode: Define a function constructor, as an object, to create an object to call the constructor directly, add the new keyword;

Constructor: A function that defines an object that contains the basic properties and methods that the object possesses;
Name capitalized, this will automatically refer to the current object;

To access object properties:
Obj[key];
Obj.key;

To traverse an object:
for (key in obj) {
Key is the attribute name;
Obj[key] is the value of the attribute;
}
21. JSON
{
"Name": "Li Guo",
"Age": 18,
"Color": "Yellow"
}

1. All attribute names must be wrapped in double quotation marks;
2, the literal emphasis on the description object, JSON focus on data transmission;
3, JSON does not support undefined;
4, JSON is not an object, JSON sent from the server is generally a string,
It can be converted to JS object by Json.parse (Jsondate.json);
22. JS Parsing
(1), scope
Global scope: The entire code can be called everywhere;
Local scope: A variable declared inside a function that can only be used inside a function;

(2), variable promotion and function promotion
Pre-parsing: At the time of parsing, Var and function will be promoted to the top of the code;
But assignment operations are not promoted, and definitions and functions are promoted;
If the definition of the variable is also promoted, but the assignment operation will not;
23. Other details (tips)
(1), the element is sorted by an array of objects
eg
var data = [
{title: "Old Driver", count:20},
{title: "Poet", Count:5},
{title: "Singer", Count:10},
{title: "The Old king next Door", count:30},
{title: "Sailor", Count:7},
{title: "Gourd Doll", count:6},
];
The elements of the array are objects. We need to reorder the arrays based on the value of count.
Solution: Use the Sort method to tamper with the incoming function.

    function sortArr(a,b){        return a.count > b.count;       }    data.sort(sortArr);        //原本的a和b的比较方法变成a.count和b.count; //原本的比较方法可以参见17,数组对象 //至此,data将以count值从小到大排列。tips:Array对象的sort方法传入的为比较函数,比较函数里return排序比较的方法; 原始的sort方法传入的函数内部return的值为a>b, 通过修改sort传入的函数,可以实现对元素为对象的数组的排序!

JS Basic syntax

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.