Primary knowledge of JS basic syntax. Basic operators

Source: Internet
Author: User
Tags array sort script tag alphanumeric characters

JavaScript Overview of JavaScript history
    • 1992 Nombas developed the embedded scripting language for C-minus-minus (c--) (originally bundled in Cenvi software). Rename it scriptease. (The language that the client executes)
    • Netscape (Netscape) received Nombas's philosophy, (Brendan Eich) developed a set of Netscape scripting languages in its Navigator livescript 2.0 product. Sun and Netscape are done together. And then the name is JavaScript.
    • Microsoft then emulated a JavaScript clone called JScript in its IE3.0 product.
    • To unify the three, the ECMA ( European Computer Manufacturing Association) defines the ECMA-262 specification. The International Organization for Standardization (ISO/IEC) also adopted ECMAScript as the 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 the norm.
ECMAScript

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 following 3 different parts:

    • Core (ECMAScript)
    • Document Object Model (DOM) Documents object models (consolidated js,css,html)
    • Browser object models (BOM) Broswer object Model (integrated JS and browser)
    • The vast majority of Javascript in development is object-based. It is also object-oriented.

To put it simply, ECMAScript describes the following:

    • Grammar
    • Type
    • Statement
    • Key words
    • Reserved words
    • Operator
    • Object (encapsulates inherited polymorphism) object-based language. Use an object.
how JavaScript is introducedwrite code inside the script tag
<script>  //write your JS code here </script>
Introduction of additional JS files
<script src= "Myscript.js" ></script>
JavaScript Language SpecificationNotes
This is a single-line comment/* This is a multiline comment */
Terminator

The statements in JavaScript are terminated with a semicolon (;)

JavaScript Language BasicsVariable Declaration

The variable name of JavaScript can be composed of _, number, letter, $, and cannot begin with a number.

declaring variables using var variable names; The format to declare

var name = "Alex"; var age = 18;

Attention:

Variable names are case-sensitive

Camel-named rules recommended

A row can declare multiple variables. And can be of different types

var name= "Yuan", age=20, job= "lecturer";

You can declare variables without var. If you don't use Var then it's a global variable

Variable name, the first character can only be letter, underscore, $ dollar symbol three select one, the remaining characters can be underscores, dollar signs or any alphanumeric characters and case-sensitive, x and X is two variables

Constants and Identifiers

Constants : Data values that appear directly in the program

Identifier:

Consists of letters, numbers, underscores (_), Dollar signs ($) that do not begin with a number

A name commonly used to denote functions, variables, etc.

For example: _ABC, $ABC, abc,abc123 is an identifier, and 1ABC is not

Words that represent a particular meaning in the JavaScript language are called reserved words and do not allow programs to be redefined as identifiers

JavaScript data types

JavaScript has a dynamic type

var x;  At this point x is Undefinedvar x = 1;  At this point x is the number var x = "Alex"  
Number Type

JavaScript does not differentiate between integral and floating-point types, there is only one numeric type

var a = 12.34;var b = 20;var c = 123e5;  12300000var d = 123e-5;  0.00123

Common methods for converting numbers

parseint ("123")  //Return 123parseInt ("ABC")  //Return Nan,nan property is a special value that represents a non-numeric value. This property is used to indicate that a value is not a number. Parsefloat ("123.456")  //Return 123.456
String

is a sequence of Unicode characters, numbers, punctuation marks, string constants are enclosed in single or double quotation marks, and there are no character types in JavaScript, and expressions of common special characters in strings;
Some special characters in a string must be accompanied by a right dash \; Common escape character \ n: newline \ ': single quote \ ': double quote \ \: Right Dash

String Object creation

String creation (two ways)
variable = "string"
Word string Object name = new String (string)

var str1= "Hello World"; var str1= new String ("Hello word");

Common methods of strings

 X.length-----get the length of the string X.tolowercase ()---to lowercase x.touppercase ()----to uppercase X.trim ()--- Remove whitespace x.trimleft ()----remove the left space of the string x.trimright ()----Remove the string to the right of the space---string Query method X.charat (index)----str1. CharAt (index);-------get the specified position character, where index is the character index to get X.indexof (findstr,index)----the location of the query string element, cannot find the return -1x.lastindexof (findstr                        ) X.match (RegExp)----match returns an array of matching strings, and returns Nullx.search (REGEXP)----search returns the first character position index of the matched string if there is no match                        Example: Var str1= "Welcome to the world of js!";                        var str2=str1.match ("World");                        var str3=str1.search ("World");  Alert (str2[0]);     The result is "world" alert (STR3); The result is 15----substring processing method x.substr (start, length)----start represents the start position, length indicates the Intercept length x.substring (start, end)-- --end is the end position x.slice (start, end)------slice manipulation string, you can use negative example: var str1= "abcDefgh ";                            var str2=str1.slice (2,4);                            var str3=str1.slice (4);                            var str4=str1.slice (2,-1);                            var str5=str1.slice ( -3,-1); alert (STR2); The result is "CD" Alert (STR3); The result is "EFGH" alert (STR4); The result is "CDEFG" alert (STR5);                 The result is "FG" X.replace (FINDSTR,TOSTR)---string substitution x.split ();                                 -----split string var str1= "One, two, three, four, five, six, day";                                var strarray=str1.split (","); Alert (strarray[1]);//result is "two" X.concat (ADDSTR)-----stitching string

Splicing strings generally use "+"

Boolean type

Different from python,true and false are lowercase

The 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 correspondence True/false

var a = True;var B = false;
Array

Similar to the list in Python

Three ways to create an array

Creation method 1:var Arrname = [element 0, Element 1,....];          var arr=[1,2,3]; creation method 2:var arrname = new Array (element 0, Element 1,....); var test=new array ("A", "true"), creation mode 3:var arrname = new Array (length);  Initialize Array object:                var cnweek=new array (7);                    Cnweek[0]= "Sunday";                    Cnweek[1]= "Monday";                    ...                    Cnweek[6]= "Saturday";

How to use arrays

Join Method X.join (BYSTR)----stitch array elements into string var arr1=[1, 2, 3, 4, 5, 6, 7];                var str1=arr1.join ("-");  alert (STR1);    The result is "1-2-3-4-5-6-7"//Concat method X.concat (value,...)                  -----concatenate array var a = [n/a];                  var b=a.concat (4,5);  Alert (a.tostring ());  The returned result is a b.tostring (). Returns the result for the 1,2,3,4,5//array sort-reverse sort//x.reverse ()//x.sort () var arr1=[32, 111, 444];//var arr1=["a", "D", "F", "C"; Arr1.reverse ();  Reverses the array element alert (arr1.tostring ());    ToString () converts the array to a string and returns the result//result to 444,111,12,32arr1.sort (); Sort array Element alert (arr1.tostring ());//result for 111,12,32,444//------------------------------Arr=[1,5,2,100];//arr.sort () //alert (arr);//If you want to compare by numbers? Function Intsort (A, B) {if (a>b) {return 1;//-1} else if (a<b) {RE TURN-1;//1} else {return 0}}arr.sort (intsort), alert (arr), function Intsort (A, b) {return a-A;} Array slicing operation//x.slice (start, End)//x represents the Array object//start represents the start position index//end is the end position the next array element index number//The first array element index is 0//start, end can be negative,-1 represents the last array element// End ellipsis is equivalent to intercepting all array elements from the start position after the Var arr1=[' a ', ' B ', ' C ', ' d ', ' e ', ' f ', ' g ', ' H '];var arr2=arr1.slice (2,4); var arr3= Arr1.slice (4); var arr4=arr1.slice (2,-1); alert (arr2.tostring ());//result is "c,d" alert (arr3.tostring ());//result is "e,f,g,h" Alert (arr4.tostring ());//result for "c,d,e,f,g"//delete sub-array//x. Splice (Start, DeleteCount, value, ...)               X represents the primary purpose of the array object//splice is to delete and insert the//start at the specified position in the index//deletecount the number of array elements to delete//value indicates that the array element that was inserted in the delete location//value parameter can be omitted var a = [1,2,3,4,5,6,7,8];a.splice]; alert (a.tostring ());//a changes to [1,4,5,6,7,8]a.splice]; alert (a.tostring ()); /a changes to [1,5,6,7,8]a.splice (1,0,2,3); alert (a.tostring ());//a changes to [1,2,3,5,6,7,8]//array's Push and Pop//push pops. The two methods simulate a stack operation/  /x.push (value, ...) Stack//x.pop () The stack//x represents an array object//value can be a string, a number, an array, and any value//push is to add value values to the end of the array x//pop is to remove the last element of the array x var arr1=[1,2,3]  ; Arr1.push (4,5); alert (arr1);//result is "1,2,3,4,5" Arr1.push ([6,7]); alert (ARR1)//result for "1,2,3,4,5,6,7" Arr1.pop (); Pop canFetch the deleted value alert (ARR1);//The result is "1,2,3,4,5"//Array Shift and Unshift//x.unshift (value,...) X.shift ()//x represents an array object//value can be a string, a number, an array, and any value//unshift is the beginning of inserting value value into the array x//shift is the first element of the array x is removed var arr1=[1,2,3];  Arr1.unshift (4,5); alert (ARR1); The result is "4,5,1,2,3" arr1.  Unshift ([6,7]); alert (ARR1);  The result is "6,7,4,5,1,2,3" Arr1.shift (); alert (ARR1); The result is "4,5,1,2,3"

Summarize the array characteristics of JS

The attribute of an array in  JS         //java, specifies what  type of array it is, and only what type it is. There is only one type.         The array attribute in JS 1:js can be any type, without any restrictions.         The array attribute in JS is 2:js, and the length is changed with the subscript. How long it will take.         var arr5 = [' abc ', 123,1.14,true,null,undefined,new String (' 1213 '), New Function (' A ', ' B ', ' Alert (a+b) ')];  /* alert (arr5.length);//8         arr5[10] = "hahaha";         alert (arr5.length);         alert (arr5[9]);//undefined */
Object

Data types other than null and undefined are defined as objects in JavaScript, and variables can be defined using the method of creating objects, String, Math, Array, Date, RegExp are important built-in objects in JavaScript, and most of the functionality in JavaScript programs is based on object implementations.

<script language= "javascript" >var Aa=number.max_value; Use a numeric object to get the maximum number of Var bb=new String ("Hello JavaScript"); Create a String object var cc=new date ();//Create Date object var dd=new Array ("Monday", "Tuesday", "Wednesday", "Thursday"); Array Objects </script>

Create a dictionary-like object

var a = {"name": "Alex", "Age": 18};console.log (A.name); Console.log (a["age"]);
null and undefined

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. A 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. If the function or method is to return an object, the object returned is usually null when it is not found.

Type query
typeof "ABC"  //"string" typeof null  //"Object" typeof true  //"Boolean" typeof 123//"Number" Console.log ( typeof ([11,22]));  Objectconsole.log (typeof ("123"));  String

typeof is a unary operator (like ++,--,! ,-equal unary operator), not a function, nor a statement

Operator
Arithmetic operator:    +   -    *    /     %       + +-        -comparison operator:    >   >=   < <=!    =    = =    = = = = =   !== logical operator:     &&   | |   ! Assignment operator:    = = = =  *=   /= string operator:    +  join, either side operand has one or two is a string do join operation

i++ the first assignment and then calculate the value
++i calculate the re-assignment first

= = = Strong equals, both judging value and judging type

Note 1:

On both sides of the comparison operator if one is a numeric type and one is a different type , its type is converted to a numeric type .

If both sides of the comparison operator are string types , the highest bit ASC code is compared, and if the highest bit is equal , continue to take the second bit comparison

NOTE 2:

JS Unlike Python, it is a weakly typed language

Static type language

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 languages

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 languages

A type of language that can be ignored, as opposed to a strong type. JS is a weak type. In js, the string ' 12 ' and the integer 3 can be concatenated to get the string ' 123 ', which can then be considered as an integer 123, all of which do not require any display conversion.

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 )

Process ControlIf-else
if (expression) {   statement 1;   ......   } else{   statement 2;   .....   }
If-else If-else
if (expression 1) {    statement 1;} else if (expression 2) {    statement 2;} else if (expression 3) {    statement 3;} else{    statement 4;}
Switch
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;}

Default value when none of the above conditions are satisfied

If you do not add a break, you will continue to break from the beginning of the qualifying

For
for (Var i=0;i<10;i++) {  console.log (i);} Another form of For loop for (variable in array or object)    {        EXECUTE statement ...        }
While
var i = 0;while (i <) {  console.log (i);  i++;}
Ternary operations
var a = 1;var b = 2;var c = a > B? a:b//condition is set up to take a, does not establish take B

Primary knowledge of JS basic syntax. Basic operators

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.