1. Six ways to create a variable
A variable is not a specific value, but a container or pronoun used to store specific references. Because the value stored in a variable can be changed, it is called a variable.
Based on the ES syntax, there are several ways to create variables in JS.
- var (ES3)
- Function (ES3) creates a function (the function name is also a variable, but the value stored is of the function type)
- let (ES6)
- Const (ES6) creates a constant
- Import (ES6) Export required information based on ES6 module specifications
- Class (ES6) Creates classes based on ES6
Var [variable name] = [value]; * let [variable name] = value; * const [variable name] = [value]; * function function name () {* *} *... * /
var n = 13;
n = 15;
alert(n+10); // => pop up 25, where n represents 15
const m = 100;
m = 200; // Uncaught TypeError:Assignment to constant variable. A constant cannot be reassigned (the value stored in a constant cannot be changed; only variables can be changed)
Copy the code
2. Naming conventions in JS
- Strictly case sensitive
- Follow the camel’s name: Use numbers, letters, and underscores (numbers do not start names with digits), and combine them into a full name based on English words (lowercase first word, uppercase first letter of every meaningful word).
- Do not use keywords and reserved words (in JS, words that have special meaning are called keywords, and words that may become keywords in the future are called reserved words)
var n = 12; var N = 13; //=> Two n/ n variables are different var studentInfo/student_info / _studentInfo(public variables) / $studentInfo(JQ elements)... Add/create/insert/delete/update/remove/info/detail/logCopy the code
3. Classification of data types
A data value is a material produced in a language, and JS contains values of the following types
- Basic data types (value types)
- Digital number
- String string
- Boolean Boolean
- null
- undefined
- Reference data type
- Object the object
- Ordinary objects
- The array object
- Regular object
- The date object
- .
- Function is the function
- Object the object
- A special type has been added to ES6 :Symbol, a unique value
Var n = 13; Var s = "; // => 0; // => 0; Var b = true; //=>"" '13' "{}" var b = true; Var o = {name: 'ZFPX ', age: 9}; Var ary = [12,23,34,45]; var ary = [12,23,34,45]; //=> enclose parentheses containing zero to multiple items, which are array objects. [] var reg = /-? (\d|([1-9]\d+))(\.\d+)? /g; Function fn () {} [Symbol] var a = Symbol(' Everest '); Var b = Symbol(' Everest '); console.log(a == b); // falseCopy the code
How the JS code is run and how it outputs the results
- Running code in a browser (browser kernel for rendering and parsing)
- Run on NODE (which is also a tool for rendering and parsing JS based on V8 engine)
[How to output results]
- Alert: output by pop-up in the browser (browser prompt box)
var num = 12; alert(num); //window.alert var str = 'zfpx'; alert(str); All output based on alert is converted to a string: the value (evaluated first if an expression) is converted to a string using the toString method, and alert(1+1) is printed. // '2' alert(true); / / = > 'true' alert ([12, 10]); / / = > '12, alert ({name: "XXX"}); //[Object Object] why?Copy the code
- Confirm: Confirm: Alert: Confirm: Confirm: Alert: Cancel: Confirm: Confirm: Alert: Cancel: confirm
Var flag = confirm(' do you want to exit '); If (flag) {//=>flag:true user clicks ok button} else {// false user clicks cancel button}Copy the code
- Prompt: Add input fields to confirm
- Console. log: Outputs logs on the browser console
- Elements: The Elements and styles of the current page can be seen here, and the structure can be modified, etc
- Console: the Console, which can be output in JS code via.log, or directly write JS code
- Sources: The source files for the current site are all here
.
- Console. dir: more detailed than log output (especially when output object data values)
- Console. table: Outputs a JSON data as a table
-… (Go back and extend more console output yourself)
4. Number data types (NaN and isNaN)
- Number Number type
NaN: not a number but it is of numeric type isNaN: checks if the current value is not a significant number, returning true for a significant number and false for a significant number
//=> syntax: isNaN([value]) var num = 12; isNaN(num); False isNaN(' Everest ') => True isNaN(true) => false isNaN(false) => False isNaN(false) => False IsNaN (null) => false isNaN(undefined) => True isNaN({age:9}) => True isNaN([12,23]) => True isNaN([12]) => false IsNaN (/^$/) => true (function() {}) => true The browser converts values to numbers by default. Converts non-numeric values to numbers - Other basic types to numbers: [string to Number] Number('13') -> 13 Number('13px') -> NaN NaN Number('13.5') -> 13.5 can recognize decimals Number(true) -> 1 Number(false) -> 0 [other] Number(null) -> 0 Number(undefined) -> NaN - Converts the reference data type to a Number: ToString = toString; toString = Number; toString = Number; toString = Number; toString = Number;Copy the code
5. Boolean types and null and undefined
Boolean type: only two values true/false
How do I convert other data types to Booleans
- Boolean
- !
- !!!!!
Boolean(1) - >true
Boolean(0) - >false
Boolean(-1) - >true
Boolean(NaN) - >false
!'Everest'=> Convert other data types to Booleans first and then invert!!null= >If you take two inverts, that's the same thing as taking no inverts at all, you're just left with a Boolean conversionCopy the code
Rule: in JS, only “0,NaN,””,null,undefined” are converted to Boolean false, the rest are converted to true
null && undefined
Represents an empty
- Null: Indicates an empty object pointer
- Undefined undefined
Null is usually not expected. This is usually done manually. We will assign it again later.
var num = null; // =>null is a manual assignment, indicating that I will change the value of the num variable later. num =12;
Copy the code
Undefined means nothing, usually not manually controlled, most of the browser self-help empty (can be assigned or not assigned)
var num; // => The browser assigns the value of the variable to be undefined. It may or may not be assignedCopy the code
6. General operations on object data types
Ordinary objects
- Wrapped in braces
- Consists of zero to multi-log stars and attribute values (key-value pairs)
Attribute is used to describe the current characteristics of the object, the attribute name is the current possession of the feature, the attribute value is the description of the feature (professional syntax, the attribute name is a key, the attribute value is a value, a set of attribute names and attribute values is a set of key-value pairs)
var obj = {
name: "Everest".age: 9
}
//=> Object operations: add, delete, change, and check key/value pairsSyntax: object. Property name/object [property] obj. Name obj['name'In general, object attribute names are in string format (attribute values are not fixed, any format can be used)'zfpx'; //=> The name attribute name exists in the original object, which belongs to the modified attribute name
obj.sex = 'male'; //=> There is no sex in the original object. This is equivalent to adding a new attribute sex to the current object
obj['age'] = 28; // => Modify attributesDelete: This attribute no longer exists in the objectdelete obj['age']; False delete: Does not remove the number property, but makes the current property null obj.sex =null; When retrieving an attribute value, if the current object has the attribute name, the value can be retrieved normally (even if it isnull), but without this property, the result obtained isundefined
obj['friends'] = >undefined
Copy the code
[B].
var obj = {
name: 'Everest'.age: 9
};
var name = 'zhufeng';
console.log(obj.name); // 'Mount Everest'
console.log(obj['name']); // 'Mount Everest'
console.log(obj[name]); 'zhufeng' obj['zhufeng'] => There is no such attribute, the attribute value is undefined
---------
'name'And name? = >'name'Is a string value, it represents the thing itself => name is a variable not a value, it represents the value itself storedCopy the code
Attribute names in an object are not only in string format, but may also be in numeric format
Var obj = {name: 'mount ', 0: 100}; obj[0] => 100 obj['0'] => 100 obj.0 => Uncanght SyntaxError: Unexpected Number ------- When we store property names that are not strings or numbers, the browser will convert the value to a string (toString), and then store obj[{}]=300; Obj ['[object object]']= > Obj [{}] => Convert the object to the string '[object object]', and then get 300 ---- array objects (objects consisting of key-value pairs) var oo = {a: 12} var ary = [12,23]; //=>12 and 23 are attribute values. When we look at the result, we see that the array object's attribute name is a number (we call the number attribute name the index of the current object) ary[0] ary['0'] ary.0 => error syntaxCopy the code
7. How JS works (stack memory and how different data types operate)
var a = 13; var b = a; b = 13; console.log(a); var obj1 = {n: 100}; var obj2 = obj1; obj2['n'] = 200; console.log(obj1.n); When the browser (its kernel engine) renders and parses JS, it provides an environment for the JS code to run. We call this environment "global scope" * 2. * 1) first create a space to store 12 * 2) declare a variable in the current scope (var a) * 3) associate the declared variable with the stored 12 (assigning the stored 12 to a=> definition) * * Basic data types (also called value types) operate on values: * * => The value of the reference data type cannot be stored directly in the current scope. We need to create a new space first. * var obj1 = {n: 100}; * 1) first of all, create a new memory space, the object of key/value pairs stored in sequence (in order to ensure that can be found behind the space, this space has a hexadecimal address) declare a variable * * 2) (3) let variables and space address associated together (the space address assigned to a variable) * * reference type is not in accordance with the value to the operation, It operates the reference address of the space: assign the address of the original space to the new variable, but the original space has not been cloned, or a space, so it will bleed the line of multiple variables associated with the same space, there will be influence between each other. */ var obj = {n: 10, m: {obj = {n: 10, m: {obj = {n: 10, m: {obj = {n: 10, m: {obj = {n: 10, m: {obj = {n: 10, m: {obj = {n: 10, m: {obj = {n: 10, m: {obj = {n: 10, m:} obj.n * 10 } console.log(obj.m); //=>Uncaught TypeError: Cannot read property 'n' of undefined /** * 1 * n:10 * m:obj. N *10 =>obj. N At this time, the heap memory information has not been stored, the address of the space is not given to OBj, at this time obj is undefined. Obj. n<=>undefined. N */ var ary1 = [3,4]; var ary2 = ary1; ary2[0] = 1; Ary2 = [4, 5); ary2[1] = 2; ary1[1] = 0; console.log(ary1,ary2); // [1, 0], [4, 2]Copy the code
8. The judgment operation statement in JS
- if / else if / else
var num = -6; if (num>10) { num++; }else if (num>=0 &&num <=10) {num--; }else{ num+=2; } console.log(num); / / - 4Copy the code
As long as one condition is true, the following conditions, whether it is true or not, are no longer judged to be executed
var num = 10; if (num>5) { num+=2; }else if(num>8) { num+=3; }else{ num+=4; } console.log(num); / / 12Copy the code
What can I write about conditions?
// >= <= == if (0) {//=> Whatever you write in a condition, always evaluate it to true/false to determine whether the condition is true. } if('3px'+3) {//=> if('3px'+3) {//=> } //=>+;} //=>+;} //=>+;Copy the code
Var num = parseInt (' width: 35.5 px); If (num = = 35.5) {alert (0); }else if(num==35) { alert(1); }else if(num==NaN){ alert(2); }else if(typeof num=='number') {// if(typeof num=='number'); }else{alert(4); }Copy the code
9. Ternary operators and switch cases
1, ternary operator syntax: conditional? 2. Something that is not valid to do; <=> is equivalent to a simple if/else judgment
var num = 12; if (num>10) { num++; }else{ num--; } // num>10? num++:num--;Copy the code
A special case
//=> If a part of the ternary operator does not need any processing, we use null/undefined/void 0... Var num = 12; num>=10? num++:null; (num = 10); (num = 10); (num = 10); num>=10? (num++,num*=10):null;Copy the code
[Thinking question] : Change to ternary operator
var num = 12; if (num>0) { if(num<10) { num++ }else{ num--; } }else{ if(num==0) { num++; num=num/10; }}Copy the code
2. A judgment method in switch Case JS
var num = 12; if (num==10) { num++; }else if(num==5){ num--; }else{num=0} //=> switch case switch(num) {case 10: num++; break; case 5: num--; break; default: num=0; } //=>switch case applies to different operations on variables (or expressions, etc.) with different values. A break is required for each caseCopy the code
'10'==10 =>true ('10'==10, '10'===10, '10'===10, '10'===10); Var num = 12; var num = 12; var num = 12; switch(num) { case 10: case 5: num--; break; default: num=0; } //=> if break is not set, the following condition will be executed regardless of whether it is true; Using this mechanism, we can do some special processing, for example: if num = 10 and num = 5 both want to do the same thing, let's write them together without adding breakCopy the code
10. The basic operation mechanism of the for loop
1. For loop
What it does: To do something over and over on a regular basis, we need to use a loop.
Var ary =,23,34 [12]; /** * loop through each item in the array */ for (var I = 0; i < ary.length; I ++) {//=> first loop: I =0 I <3... I =1 //=> first loop: I =1 I <3... I =2 //=> first loop: I =2 I <3... I =3 //=> first loop: I =3 I <3 end of loop (no loop this time) console.log(ary[I]); Var I = 0; var I = 0; I < ary.length * 3. Conditional creation executes the contents of the body of the loop (which is wrapped in braces) * 4. For (var I = ary.length-1; var I = ary.length-1; i >= 0; i--) { console.log(ary[i]); } for (var I = 0; i < ary.length; i++) { if (i % 2 === 0) { console.log(ary[i]); } } for (var i = 0; i < ary.length; i+=2) { console.log(ary[i]); }Copy the code
In the body of a for loop, there are two common keywords: /** * 1. Continue: continue * 2. Break: break or terminate */Copy the code