JavaScript&ES6 knowledge points

JavaScript&ES6

JavaSCript :

data type

  • Simple data types: Number, String, Boolean, Undefined, and Null
  • Complex data type: Object
  • Get variable type: typeof
  • Data type conversion: toString(), String(), num + "", Number, parseInt(str), parseFloat(str), Boolean()
  • Implicit conversion of boolean type:
  • Convert to true: non empty string, non-0 string, non-0 number, true, any object
  • Convert to false: empty string, 0, false, null, undefined

array

Definition, acquisition, traversal, replacement and addition of array:

//  Definition
var arr = [ "red","green","blue"]
// Obtain
console.log(arr[0]);
// ergodic
arr.forEach(el =>{
    // Array traversal
    console.log(el);
});
// replace
arr[0] = "yellow";
// Newly added
arr[3] = "pink";

function

  • Use of arguments:
// agruments: 
 function pringArgs(){
     console.log(arguments);
 }
 pringArgs("A",'a',0,{
    foo:"Hello"
 });
  • Self calling of anonymous function:
// Self calling of anonymous function
(function(){
    alert(124);
})();
  • Function as return value:
// Function as return value
function fn(b){
  var a = 10;
  return function(){
      alert(a+b);
  }
}
fn(15)();
  • Scope:
    • Global variables: do not use the variables of var life (not recommended), close the web page or browser before destroying
    • Local variable: a variable that can be accessed by a fixed code fragment, such as within a function
    • Lexical scope:
      • Function allows access to data outside the function
      • Only functions can be scoped in the whole code structure
      • If there is a name in the current action rule, the external name will not be considered
var num =123;
function foo(){
   console.log(num);
}
foo();
//Output: 123
if(false){
  var num = 123;
}
console.log(num);
//Output: undefined
  • Closure function:
  • A closure is a function that has access to variables in the scope of another function
  • Simple understanding: one scope can access local variables inside another function
  • Functions: extending the scope of a variable
//Example of closure function:
var car =(function(){
var start = 13;
var total = 0;
return {
    // Normal total price
price:function(n){
if(n<=3){
 total = start;
}else{
    total = start + (n-3) * 5;
}
return total;
    },
    // Cost after congestion
    yd:function(flag){
 return flag ? total +10 :total;
    }
}
 } )();
  • Recursion:
    • If a function can call itself internally, it is a recursive function
    • Recursive functions work just as well as loops
    • Because recursion is prone to stack overflow, you must add a return condition
//Factorial example:
    var n;
    var m =fact( n=prompt("Please enter a number:"));
    document.write(n+'The factorials of are:'+m);
    function fact(n) {
    if (n <= 1) {
             return 1;
    } else {
             return n * fact(n - 1);
    }
}
//Fibonacci series example:
var n=prompt("Please enter a number:");
function fib(n){
if(n==1||n==0){
    return 1;
}
else {
    return fib(n-1)+fib(n-2);
}
}
alert(fib(n));

ES6:

New variable declaration method

  • let / const
    • Different from var, the new variable declaration method brings some different features, the most important two of which are providing block level scope and no longer having variable promotion
    • let: non repeatable declaration, block level scope. const: declare a constant.
var let const
Function scope Block level scope Block level scope
Variable lifting No variable promotion No variable promotion
Value can be changed Value can be changed Value cannot be changed

Destructuring assignment

  • Deconstruction assignment syntax is a kind of javascript expression, which is used to distinguish the values in an array or the attributes in an object into different variables.
  • It can be divided into object deconstruction assignment and array deconstruction assignment.
  • Example: define an object to represent a point in three-dimensional space, and use these coordinate points for square operation.

Deconstruction replication of objects

        //Deconstruction and assignment of objects
        let newPoint={
            x:2,
            y:3,
            z:4
        };
        let{x,y,z}=newPoint;
        // sqrt square root function toFixed: keep decimal places
        console.log(Math.sqrt(x*x + y*y + z*z).toFixed(2));

Deconstruction replication of arrays

let newPoint = [2,4,5];
let [x,y,z]=newPoint;
console.log(Math.sqrt(x*x + y*y + z*z).toFixed(2));

Arrow function

  • Arrow functions are used instead of anonymous functions
  • It is equivalent to abbreviated function, replaced by * * () *, replaced by = > instead of {}
//Without parameters
var show2 = () => console.log("hello,world");
show2();
//Band parameters
var show4 = (name)=>console.log(name);
show4('happiness');
  • Pass two parameters to implement an add function that calculates the sum of two numbers: pass two parameters must be wrapped in brackets
  • If you use return to return an execution statement, you can omit return
var add2 = (a,b)=>{
    return a+b;
}
console.log(add2(1,2));

Ellipsis return

var add3 = (a,b)=>a+b;
console.log(add3(1,2));

Residual parameters

  • ... Used to declare the remaining parameters, a,b are named parameters c is used to collect the remaining parameters
      // Residual parameters
      function show(a,b,...c){
           console.log(a);
           console.log(b); 
           console.log(c);
      }
      show(1,2,4,6,7,9);

Parameter template (template string)

  • Template strings are used to solve the inconvenience of splicing strings with "+"
  • It's very powerful, but most of the time it's very simple to use
  • ${variable name / constant name}, wrapped in back single quotes
    // String emulation
    let a='hello';
    let b='world';
    let c= `${a,b}`;
    let d=`${a} ${b}`;
    console.log(c);
    console.log(d);
    // Support for operations
    let x=1;
    let y=2;
    let result = `${x+y}`;
    console.log(result);

Array method

  • Array.from(json): convert a json string to an array. The json string must have a length attribute
// json array format conversion
let json={
    '0':'niit',
    '1':'computer',
    '2':'mobile',
    length:3
}
let arr1= Array.from(json);
console.log(arr1);
  • Instance method find(): search from the array and pass in an anonymous function with 3 parameters
    • Value: the value of the current lookup
    • Index: the index of the currently found array
    • arr: current array
//lookup
let arr= [1,2,3,4,5,6,7,8,9];
console.log(arr.find(function(value,index,arr){
    return value >5;
}));
  • Instance method fill (value, start, end): use the given value to fill the array, the original elements in the array will be erased, starting from the position start to fill, excluding the end position
// Fill
let arr= [1,2,3,4,5,6,7,8,9];
arr.fill(1,2,5);
console.log(arr4);
  • Traversal arrays can use for of or next() traversal
    • entries(): key value pair traversal
    • keys(): key name traversal
    • values(): key traversal
// Array traversal
let arr = ['niit','conputer','mobile'];
// Output index
for(let index of arr.keys()){
    console.log(index);
}
// Output value
for(let index of arr.values()){
    console.log(index);
}
// Output index and content
for(let [index,val] of arr.entries()){
    console.log(index+":"+val);
}
// entries() method
let list = arr.entries()
console.log(list.next().value);
  • Array—map
  • map(): returns a new array whose elements are the values after the original array elements call the function to process
  • For example, an array stores the scores of 6 students, 60 or more shows pass, otherwise shows fail, and displays pass / fail in a new array according to the order of scores.
// map
let scores = [25,79,67,85,88,63];
let scores1 = scores.map(score =>{
if(score>=60){
    return "pass";
}else{
   return "Fail,";    
}
})
console.log(scores);
console.log(scores1);
  • Array—reduce
  • reduce(): the receiver function acts as an accumulator, the elements of the array are reduced from left to right, and finally calculated as a value
  • Example: convert array [1,3,5,7,9] to 13579
let arr=[1,3,5,7,9];
let result=arr.reduce((x,y)=>(x*10+y));
console.log(result);
  • Array—filter
  • filter(): create a new array. The elements in the new array are checked by checking all the qualified elements in the specified array
  • Example: select even elements in the array:
let scores = [23,45,76,85,12,91];
console.log(scores.filter((item)=>item%2==0));
  • Array—forEach
let scores  =[23,45,76,85,12,91];
scores.forEach((item,index)=>{
    console.log(`The first${index}Element`+'yes'+item);
})
Published 6 original articles, won praise 0, visited 113
Private letter follow

Tags: JSON Javascript Mobile Fragment

Posted on Fri, 13 Mar 2020 07:10:02 -0700 by slweb