JavaScript language basics
variable declaration
- JavaScript variable names can be composed of _, numbers, letters, and $, and cannot start with numbers.
- Declare variables using the format var variable name;
var name = "Alex"; var age = 18;
Notice:
Variable names are case-sensitive.
CamelCase is recommended.
Reserved words cannot be used as variable names.
abstract boolean byte char class const debugger double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized throws transient volatile
JavaScript data types
JavaScript has dynamic typing
var x; // now x is undefined var x = 1; // now x is a number var x = "Alex" // now x is a string
Number type
JavaScript doesn't differentiate between integers and floats, there is only one numeric type.
var a = 12.34; var b = 20; var c = 123e5; // 12300000 var d = 123e-5; // 0.00123
There is also a NaN, which means Not a Number.
Common method:
parseInt("123") // returns 123 parseInt("ABC") // Returns NaN, the NaN property is a special value representing a non-numeric value. This property is used to indicate that a value is not a number. parseFloat("123.456") // returns 123.456
string
var a = "Hello" var b = "world; var c = a + b; console.log(c); // get Helloworld
Common method:
method | illustrate |
.length | return length |
.trim() | remove whitespace |
.trimLeft() | remove white space on the left |
.trimRight() | remove white space on the right |
.charAt(n) | returns the nth character |
.concat(value, ...) | splicing |
.indexOf(substring, start) | subsequence position |
.substring(from, to) | Get subsequence by index |
.slice(start, end) | slice |
.toLowerCase() | lower case |
.toUpperCase() | capital |
.split(delimiter, limit) | Split |
Concatenate strings generally use "+"
string.slice(start, stop)和string.substring(start, stop): Similarities between the two: If start is equal to end, return an empty string If the stop parameter is omitted, the end of the string is taken If a parameter exceeds the length of the string, the parameter will be replaced with the length of the string Features of substirng(): If start > stop, start and stop will be swapped If the parameter is negative or not a number, it will be replaced by 0 Features of silce(): If start > stop will not swap the two If start is less than 0, the cutting starts from the character abs(start) from the end of the string (including the character at this position) If stop is less than 0, the cut ends at the abs(stop)th character from the end of the string (excluding the character at this position)
boolean type
Unlike Python, true and false are lowercase.
var a = true; var b = false;
"" (empty string), 0, null, undefined, NaN are all false.
array
Similar to lists in Python.
var a = [123, "ABC"]; console.log(a[1]); // output "ABC"
Common method:
method | illustrate |
.length | the size of the array |
.push(he) | append element at the end |
.pop() | get the element at the end |
.unshift (ele) | head insert element |
.shift() | head remove element |
.slice(start, end) | slice |
.reverse() | reverse |
.join(seq) | Concatenate array elements into a string |
.concat(val, ...) | concatenating arrays |
.sort() | sort |
Notice:
/* If the sort method is called with no parameters, the elements in the array will be sorted alphabetically, or more precisely, in the order of character encoding. To do this, first convert the elements of the array to strings (if necessary) so that they can be compared. 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, and its return value is as follows: If a is less than b, a should appear before b in the sorted array, a value less than 0 is returned. Returns 0 if a is equal to b. If a is greater than b, a value greater than 0 is returned. */ // Implement a sorting function by yourself according to the above rules: function sortNumber(a,b) { return a - b } // When calling the sort method, you can pass in the defined sorting function. stringObj.sort(sortNumber)
Type query
typeof "abc" // "string" typeof null // "object" typeof true // "boolean" typeof 123 // "number"
typeof is a unary operator (like ++, --, !, - etc. unary operators), not a function, nor a statement.
Calling the typeof operator on a variable or value returns one of the following values:
- undefined - if the variable is of type Undefined
- boolean - if the variable is of type Boolean
- number - if the variable is of type Number
- string - if the variable is of type String
- object - if the variable is a reference or Null type
operator
arithmetic operators
+ - * / % ++ --
comparison operator
> >= < <= != == === !==
Notice:
1 == “1” // true 1 === "1" // false
Logical Operators
&& || !
assignment operator
= += -= *= /=
Process control
if-else
var a = 10; if (a > 5){ console.log("yes"); }else { console.log("no"); }
if-else if-else
var a = 10; if (a > 5){ console.log("a > 5"); }else if (a < 5) { console.log("a < 5"); }else { console.log("a = 5"); }
switch
var day = new Date().getDay(); switch (day) { case 0: console.log("Sunday"); break; case 1: console.log("Monday"); break; default: console.log("...") }
The case clause in the switch usually adds a break statement, otherwise the program will continue to execute the statement in the subsequent case.
for
for (var i=0;i<10;i++) { console.log(i); }
while
var i = 0; while (i < 10) { console.log(i); i++; }
Ternary operation
var a = 1; var b = 2; var c = a > b ? a : b
function
function definition
Functions in JavaScript are very similar to those in Python, only the way they are defined is a little different.
// normal function definition function f1() { console.log("Hello world!"); } // function with parameters function f2(a, b) { console.log(arguments); // built-in arguments object console.log(arguments.length); console.log(a, b); } // function with return value function sum(a, b){ return a + b; } sum(1, 2); // call the function // anonymous function method var sum = function(a, b){ return a + b; } sum(1, 2); // execute the function immediately (function(a, b){ return a + b; })(1, 2);
arguments
function add(a,b){ console.log(a+b); console.log(arguments.length) } add(1,2)
output:
3 2
Global and local variables of a function
local variable :
A variable declared inside a JavaScript function (using var) is a local variable, so it can only be accessed inside the function (the variable's scope is inside the function). Local variables are deleted as soon as the function finishes running.
Global variable:
A variable declared outside a function is a global variable and can be accessed by all scripts and functions on the web page.
Variable lifetime:
The lifetime of JavaScript variables begins when they are declared.
Local variables are deleted after the function runs.
Global variables are deleted after the page is closed.
scope
First, look for the variable inside the function. If you can't find it, go to the outer function to find it, and gradually find the outermost layer.
A few examples:
1.
var city = "BeiJing"; function f() { var city = "ShangHai"; function inner(){ var city = "ShenZhen"; console.log(city); } inner(); } f(); //What is the output result?
2.
var city = "BeiJing"; function Bar() { console.log(city); } function f() { var city = "ShangHai"; return Bar; } var ret = f (); ret(); // print result?
3. Closures
var city = "BeiJing"; function f(){ var city = "ShangHai"; function inner(){ console.log(city); } return inner; } var ret = f (); right();
lexical analysis
In JavaScript, the moment a function is called, lexical analysis is performed first.
The process of lexical analysis:
At the moment before the function call, an activation object will be formed: Avtive Object (AO), and the following three aspects will be analyzed:
1: Function parameter, if there is one, this parameter is assigned to AO, and the value is undefined. If not, do nothing.
2: Function local variable, if there is a value with the same name on AO, do nothing. If not, this variable is assigned to AO, and the value is undefined.
3: Function declaration, if there is one on AO, the object on AO will be overwritten. If not, do nothing.
Whether it uses parameters or local variables inside the function, it is found on AO.
Look at two examples:
var age = 18; function foo(){ console.log(age); var age = 22; console.log(age); } foo(); // Question: What is the result of executing foo()?
Second question:
var age = 18; function foo(){ console.log(age); var age = 22; console.log(age); function age(){ console.log("Hehe"); } console.log(age); } foo(); // What is the result after execution?