Getting Started with JavaScript

Source: Internet
Author: User
Tags arithmetic array sort exception handling logical operators

JavaScript outlines the relationship between ************ecmascript and JavaScript * * *November 1996, the creator of JavaScript--Netscape Company, decided to submit JavaScript to the International Organization for Standardization ECMA, hoping that the language can become an international standard. The following year, ECMA issued the standard Document No. No. 262 (ECMA-262the first edition, which specifies the standard of the browser scripting language and calls this language ECMAScript, is version 1.0. The standard was developed for JavaScript in the first place, but it was not called JavaScript, for two reasons. One is a trademark, and JavaScript itself has been registered as a trademark by Netscape. But to embody the language of the creator is the ECMA, not the Netscape, which helps to ensure the development of the language and neutrality. Therefore, the relationship between ECMAScript and JavaScript is that the former is the specification of the latter, which is an implementation of the formerECMAScript's History * * * *1992 Nombas developed C-minus-minus (c--Embedded scripting language (originally bundled in the Cenvi software). After renaming it scriptease. (The language that the client executes) Netscape (Netscape) receives the idea of Nombas, (Brendan Eich) in its Netscape Navigator2. 0 The product has developed a set of LiveScript scripting languages. Sun and Netscape are working together. After the change was called JavaScript Microsoft then imitated its IE3.0 product with a JavaScript clone called JScript. To unify the three, the ECMA (European Computer Manufacturing Association) defines the ECMA-262 specification. International Organization for Standardization (ISO) and IEC/IEC) also adopted ECMAScript as a standard (iso/iec-16262). Since then, Web browsers have struggled (albeit with varying degrees of success and failure) to ECMAScript as the basis for JavaScript implementations. ECMAScript is a specification. Year Name Description1997 ECMAScript 1First version1998 ECMAScript 2Version Change1999 ECMAScript 3 Adding a regular expression add Try/catchECMAScript4not publishedECMAScript 5 Add "strict mode"Strict mode add JSON support5.1 ECMAScriptVersion ChangeECMAScript 6adding classes and modulesECMAScript 7 Increase the exponential operator (* *Add Array.prototype.includes Note: ES6 means ECMAScript6. Although ECMAScript is an important standard, it is not the only part of JavaScript, and certainly not the only one that is standardized. In fact, a complete JavaScript implementation is made up of the following3a different part of the: core (ECMAScript) Document Object Model (DOM) documents the object model (consolidated js,css,html) of the Web browser (BOM) Broswer objects The model (integrated JS and browser) simply says that ECMAScript describes the content of the JavaScript language itself. To put it simply, ECMAScript describes the following: The syntax type statement keyword reserved word operator object (encapsulating inherited polymorphism) is based on the language of the object. Use objects. JavaScript is a scripting language JavaScript is a lightweight programming language. JavaScript is a programmatic code that can be inserted into an HTML page. When JavaScript is inserted into an HTML page, it can be performed by all modern browsers. JavaScript Basics ********1.****javascript introduced in ******scrip tag code **<script>//Write your JS code here</script>** introduction of additional JS files **<script src= "Myscript.js" ></script>2.****javascript Language Specification ****** comments * *//This is a single-line comment/*This is a multi-line comment*/* * Terminator * *the statements in JavaScript are terminated with a semicolon (;). 3.****javascript language * * * *Data Type number-----valueBoolean-----Boolean value string-----string undefined-----undefinedNULL-----NULLObject-----Object* * Variable declaration * *the variable name of JavaScript can be composed of _, number, letter, $, and cannot begin with a number. Declaring variables usingvarvariable name; The format for declaring1declaring variables without declaring variable types, all using the var keywordvarA;a= 3;2a row can declare multiple variables. And can be of different typesvarName= "Jack", Age=20, job= "loyal"; Note:1the variable name is case-sensitive. 2It is recommended to use a camel-named rule. 3reserved words cannot be used as variable names. Add:1ES6 has a new let command for declaring variables. The usage is similar to Var, but the declared variable is valid only within the block of code where the Let command resides. For example, a For loop counter is good for using the Let command. 2ES6 New Const is used to declare constants. Once declared, its value cannot be changed. 3) Keep the list abstractBooleanbyteCharClassconstDebuggerDoubleenumexportextendsfinalfloatGotoimplementsimportintInterfaceLongNativepackageprivateprotectedpublic ShortStaticsupersynchronizedthrowstransientvolatile4.****javascript Data Type * * * *JavaScript has a dynamic typevarX//at this point x is undefinedvarx = 1;//at this point x is the numbervarx = "str"//at this point, X is a string* * VALUE (number) * *JavaScript does not differentiate between shaping and floating-point types, there is only one numeric type. varA = 1.1;varA = 1;varA = 1e3;varQ = 1e-2; There is also a Nan, which means that it is not a number. Common methods: parseint ("123")//123parseint ("abc")//NaNparseint (111.1)//111parseint ("11ss")// Oneparseint ("SS11")//NaNParsefloat ("11.11")//11.11Parsefloat ("11.1ss")//11.1Parsefloat ("11.SS")// OneParsefloat ("Ss11.q")//NaN* * Strings (String) * *is a sequence of Unicode characters, numbers, punctuation marks, string constants are surrounded by single or double quotation marks, there is no character type in JavaScript, the expression of common special characters in a string, some special characters in a string must be accompanied by a right dash \; Common escape characters \ n: Line break \‘: Single quotation mark \ ": double quotation mark \ \: Right underlined var a =" Hello "var b =" word! " var C = a + Cconsole.log (c)//helloword! common method: 1) Length (This is a property is not a method, do not need parentheses) to return 2) trim () Remove string left Right end of the blank 3) trimleft () Remove the left side of the string 4) trimright () Remove the white space to the right of the string 5) charAt (n) returns the character of the string index n 6) concat        (Value,...) Stitching 7) indexOf (substring, start) returns the substring position, the first parameter is a substring, the second argument is from which position to start looking, if the substring exists return index position, there is no return 1, there is no error 8) Sub        String (from, to) gets the sub-sequence according to the index (the latter is small after the exchange, if the latter will be negative, after the exchange of negative numbers to 0 get) 9) Slice (start, end) slice (there is a negative index, find not to return an empty string) toLowerCase () Uppercase letters to lowercase one) touppercase () split () splits (if no parameters are written, output as is, if the argument is "" (The empty string, then each character is cut out)) Note: Stitching a string generally makes The difference between "+" ~~slice and substring ~~string.slice (start, stop) and string.substring (Start, stop): The same point: if Start equals end, Returns an empty string if the stop parameter is omitted, then it is taken to the end of the string if a parameter exceeds the length of the string, this parameter is replaced with the string length substirng () feature: If Start > Stop, Start and stop will be swapped if the parameter is negative or not a number, the feature of Silce () will be replaced by 0: If Start > Stop does not swap both if start is less than 0, then the cut starts with the first character of the ABS (start) from the end of the string ( Include the character of the position) if StoP is less than 0, it is cut at the end of the ABS (stop) character ending from the end of the string (not including the position character) supplement: The template string is introduced in ES6. The template string, which is an enhanced version of the string, is identified with an inverse quotation mark ('). It can be used as a normal string, or it can be used to define a multiline string, or to embed a variable in a string. Normal string ' This is a normal string! '//Multiple lines of text ' This is a multiline text '//string in the embedded variable var name = "Jack", time = "Today"; ' Hello ${name}, how is you ${time}? ' NOTE: If you need to use anti-quotes in the template string, the face Be escaped with a backslash before. Jshint Enable ES6 Syntax support:/* Jshint Esversion:6 */** Boolean (Boolean) **boolean type has only two values: True and False, also representing 1 and 0, in the actual operation true=1,false= 0 Boolean values can also be considered on/off, yes/no, 1/0 corresponding True/falsevar = True;var = false; "" (empty string), 0, null, undefined, Nan are both false**null and undefined**0.null indicate that the value is empty and is generally used when a variable needs to be specified or emptied, such as name = Null;1.undefined The type has only one value, that is, undefined. When the declared variable is not initialized, the default value of the variable is undefined. 2. When the function has no definite return value, the returned value is also "undefined"; 3.null indicates that the value of the variable is empty, and undefined means that only the variable is declared but not assigned. * * Objects (object) All things in **javascript are objects: strings, numbers, arrays, functions ... In addition, JavaScript allows custom objects to be customized. JavaScript provides multiple built-in objects, such as String, Date, Array, and so on. Objects are just special data types with properties and methods. * * Array objects are used to store a series of values using a separate variable.  var a = [1, 2,' ABC ' ];console.log (a[1]); Output 2 Common methods: Length (attribute, no parentheses required) array size push (ele) tail append element pop () Get trailer element Unshift (ele) header Section insert element Shift () head remove element slice (start, end) slice reverse () invert join (SUP) concatenate array elements into a string concat (val        ,...) Concatenate array sort () the foreach () passes each element of the array to the callback function splice () deletes the element and adds a new element to the array map () returns An array element is called after the function has been processed by a new array of values about the sort () Note: If the method is called without parameters, the elements in an alphabetical array are sorted alphabetically, more precisely, by the order in which the characters are encoded. To do this, you should first convert the elements of the array to a string, if necessary, for comparison. If you want to sort by other criteria, you need to provide a comparison function that compares two values and returns a number that describes the relative order of the two values. The comparison function should have two parameters A and B, whose return value is as follows: If A is less than B, a value less than 0 is returned if a should appear before B in the sorted array. If a equals B, 0 is returned.                            If a is greater than B, a value greater than 0 is returned. Example: Function Sortnumber (A, b) {return A-b}var arr1 = [One, one, a, a, a, a 44]arr1.sort (sortnumber) **foreach () * * Syntax: ForE The ACH (function (currentvalue, index, arr), Thisvalue) parameter describes the function (CurrentValue, I Ndex, arr) required. The function that each element in the array needs to call。 Function Parameters: Parameter description currentva Lue required. The current element, index, is optional.                                            The index value of the current element. ARR is optional. The array object to which the current element belongs. Thisvalue is optional.                                            The value passed to the function is generally used as the "this" value. If this parameter is null, "undefined" is passed to the "This" value **splice () * * Syntax: Splice (index,howmany,item1,....., itemX) parameter Description i Ndex required.                            Specifies where to add/remove elements from. This parameter is the subscript that begins inserting and/or deleting an array element, which must be a number. Howmany required. Specifies how many elements should be deleted.                            Must be a number, but it can be "0". If this parameter is not specified, all elements from index start to the end of the original array are deleted. Item1, ..., ItemX Optional. The new element to add to the array **map** syntax: the map (function (Currentvalue,index,arr), Thisvalue) parameter describes the function (Curre Ntvalue, Index,arr) must be.                                function, each element in the array executes the function    Function parameter: Parameter description CurrentValue must. The value of the current element, index, is optional. The index value of the current element, arr, is optional. The array object Thisvalue is optional when the period element belongs to.                                    The object is used as the execution callback, passed to the function, and used as the value of "this". If Thisvalue is omitted, the value of "This" is "Undefined" supplement: ES6 introduces a new primitive data type (Symbol) that represents a unique value. It is the 7th data type of the JavaScript language. * * Type query **typeof "ABC"//"string" typeof Null//"Object" typeof True//"Boolean" typeof 123//"number" typeof is a unary operator (like + +,--,! ,-the unary operator), is not a function, nor is it a statement. Calling the TypeOf operator on a variable or value returns one of the following values: undefined-If the variable is a Boolean of type undefined-if the variable is a Boolean number-if the variable is a string of type number-if    The amount is an object of type String-if the variable is a reference type or a Null type of the * * operator **1. Operator Classification arithmetic operator: +-*/% + +-comparison operator: >   >= < <=! = = = = = = = =!== logical operator: && | | ! Assignment operator: = = = = *=/= string operator: + Join with one or two operands on both sidesis a string to do the connection operation 2. Arithmetic operator: self-increment, self-decrement ++i: First calculated after assignment i++: The first assignment is to calculate that 3.js is a weak type of language capable of data conversion is called weakly-typed Console.log ( ' 1 '==1)//trueconsole.log (' 1 '===1)//false strongly typed print (1=' 1 '//false strongly typed and weakly typed statically typed languages a language that determines the data type during compilation. Most static type languages guarantee this by requiring that their data types be declared before any variables are used. Java and C are statically typed languages. Dynamic type language A language that determines the data type during runtime, as opposed to a static type. VBScript and Python are dynamic types because they determine that the type of a variable is the first time you assign it a value. Strongly typed language a language that always enforces type definitions. Java and Python are mandatory type definitions. You have an integer that cannot be applied as a string if it is not explicitly converted. Weakly typed language A type of language that can be ignored, as opposed to strongly typed. JS is a weak type. In JS, you can set the string' 12 ' and integer 3 to connect to get string ' 123 ', and then you can think of it as an integer 123, all of which do not require any display conversions. So Python is both a dynamic type language (because it doesn't use a display data type declaration) and a strongly typed language (because it's actually the same type as long as a variable gets a data type).    4.NaNvar d= "Tom";    D=+d;        alert (d);//nan: A special value of type number, which gets a NaN data alert (typeof (D)) when it encounters an invalid to convert a string to a digit;//number//nan features: Var N=nan; alert (n>3);//false alert (n<3);//false alert (n==3);//false alert (N==nan);//false alert (N!=nan);// All of the operations that Nan participates in are false except!=5. Comparison operators: equals and non-equal operators are all equals and non-full equals.  The two operators do the same as equals and non-equals, except that they do not perform type conversions until they are checked for equality. Console.log (2==2); True Console.log (2==' 2 '); True because JS is a weak type, so returns True Console.log (2===' 2 '); False (= = = Determines the type, the type is False) Console.log (2!==' 2 '); True! = = and = = = opposite Note: var bresult = "Blue" < "alpha"; alert (bresult); Output true in the above example, the string "Blue" is less than "alpha" because the character code for the letter B is 66, and the character code for the letter A is 97. Comparing numbers and strings another tricky situation occurs when you compare numbers in two strings, such as var bresult = "3", and alert (bresult); Output "True" above this code compares the string "25" and "3". Two operands are all strings, so the comparison is their character code ("2" character code is 50, "3" character code is 51). However, if one of the operands is a number, the result is interesting: var bresult = "< 3;alert" (Bresult); Output "false" here, the string "25" will be converted to the number 25, and then compared with the number 3, the results are expected. Summary: Comparison operators on both sides if one is a numeric type and one is a different type, its type is converted to a numeric type. Comparison operator on both sides if all are string types, compare the highest bit ASC code, and if the highest bit is equal, continue to take the second bit comparison. 6. Logical operators: Console.log (1 &AMP;&AMP;3); 32 is True (0 is false, other figures represent true) Console.log (0&&3); 0 only one is False Console.log (0| | 3); 3 Console.log (2| | 3); 27. Ternary operator var a = 1;var b = 2;var c = a > B? a:b** Process Control * * Sequential structure (executed from top to bottom) branch structure looping structure * Branching structure *1.if......else structure if (expression 1) {statement 1;} else if (expression 2) {statement 2;}    else if (expression 3) {statement 3;} else{statement 4;2.switch-case structure Switch basic format switch (expression) {case value 1: statement 1;break;    Case value 2: statement 2;break;    Case Value 3: statement 3;break; Default: statement 4;} Switch than else if structureMore concise, clearer, more readable and more efficient * Loop statement *for Loop: (recommended) syntax rules: for (initial expression; conditional expression; self-increment or decrement) {EXECUTE statement ...} Another form of For loop for (variable in array or object) {EXECUTE statement ...} While loop: syntax rule: while (condition) {statement 1; ...}    * * Exception handling **try {//This code runs from top to bottom, where any one of the statements throws an exception the code block ends running}catch (e) {///If an exception is thrown in the try code block, the code in the catch code block is executed. E is a local variable that is used to point to an Error object or other thrown object}finally {//whether the code in the try code has an exception thrown (even if there is a return statement in the try block), the finally code block is always executed. } Note: Throws an exception throw error actively (' xxxx ')

Getting Started with JavaScript

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.