The difference between cookie, localStorage, and sessionStorage == the difference between let, const, and var in JavaScript == es6 deconstruction assignment

cookie、localStorage、sessionStorage区别

Cookie

Cookie was originally designed to communicate with the server, not to store it locally, it was just "borrowed" to the local store.

Insert picture description here

As shown in the figure below, every http request, the header carries cookies;

Insert picture description here

localStorage、sessionStorage

In HTML5, a new feature of localStorage/sessionStorage has been added. This feature is mainly used as local storage, which solves the problem of insufficient cookie storage space (the storage space of each cookie in the cookie is 4k), and it is generally used in localStorage. The browser supports a size of 5M.

Compared with localStorage, sessionStorage and cookie:

Insert picture description here

Differences between localStorage and sessionStorage:

Insert picture description here

What are the localStorage and sessionStorage APIs

localStorage only supports string storage.


var storage=window.localStorage;
   //写入a字段
   storage["a"]=1;
   //写入b字段
   storage.a=1;
   //写入c字段
   storage.setItem("c",3);
   //获取a 
   storage.getItem('a');
   storege.a;
   storage["a"]
   console.log(typeof storage["a"]);// string
   storage.clear();//删除所有
   storage.removeItem("a");//删除某个
   //使用key()方法,向其中出入索引即可获取对应的键
   for(var i=0;i<storage.length;i++){
    
    
       var key=storage.key(i);
       console.log(key);
   }
  //将JSON存入localStorage中,使用JSON.stringify()这个方法,来将JSON转换成为JSON字符串
  var data={
    
    
      name:'xiecanyong',
      sex:'man',
      hobby:'program'
  };
  var d=JSON.stringify(data)
  storage.setItem("data",d);
  //将JSON字符串转换成为JSON对象输出
  var json=storage.getItem("data");
  var jsonObj=JSON.parse(json);

The sessionStorage operation is the same as above

===================================================================

The difference between let, const, and var in JavaScript

table of Contents

1. Is there variable promotion?
2. Is there a temporary dead zone?
3. Is it allowed to declare variables repeatedly?
4. Is there a block-level scope?
5. Can the declared variables be modified?
In ES5only, declare variables varand functiontwo forms. But because the vardeclared variables have certain shortcomings (the problem of inner variables may cover the outer variables and the loop variables used for counting are leaked as global variables, which are introduced below), ES6the use letand constdeclaration of variables are proposed to make up ES5for varthe shortcomings in .

1. Is there variable promotion?

  • varThe declared variable has variable promotion (the variable is promoted to the top of the current scope). That is, the variable can be called before the declaration, and the value is undefined.
  • letAnd constthere is no variable promotion. That variable they must be declared in a statement after use, otherwise the report ReferenceErrorwas wrong.

console.log(f) //undefined
var f = 1 ;

console.log(g) //ReferenceError: g is not defined
let g = 2;

console.log(h) //ReferenceError: g is not defined
const h = 2;

2. Is there a temporary dead zone?

let和const存在暂时性死区. That is, as long as there is a let command in the block-level scope, the variables it declares are "bound" to this area, and are no longer affected by external influences.


var tmp = 123;
if (true) {
    
    
  tmp = 'abc'; // ReferenceError
  let tmp;
}
/*以上代码if后面{}形成了块级作用域,由于使用let声明了tmp,则这个变量就绑定了
块区域,在声明之前使用,会报错。*/

In the code block, the variable is not available until the variable is declared with the let command. This is grammatically called "temporal dead zone" (TDZ for short).
In short, the essence of the temporary dead zone is that as soon as it enters the current scope, the variable to be used already exists, but it is not available. Only when the line of code that declares the variable appears, can the variable be obtained and used.

3. Is it allowed to declare variables repeatedly?

  • var allows repeated declaration of variables.
  • Let and const are not allowed to declare variables repeatedly in the same scope.

var f = 4;
var f = 5;
console.log(5) //5

let g = 6;
let g = 7;
console.log(7) //SyntaxError: Identifier 'g' has already been declared

const h = 8;
const h = 9;
console.log(h) //SyntaxError: Identifier 'g' has already been declared

4. Is there a block-level scope?

  • There is no block-level scope for var.
  • Let and const have a block-level scope.

What is block-level scope:

The scopes in ES5 are: global scope and function scope. There is no concept of block scope. Therefore, there are also a series of problems.

//1,内层变量可能覆盖外层变量的问题
var a = 2;
function fun(){
    
    
    console.log(a) //undefined
    if(false){
    
    
        var a = 3;//变量提升带来的,尽管存在块级作用域,但是var声明的变量会跨越这个域。
    }
}
fun()
//2,用来计数的循环变量泄露为全局变量。
var s = 'hello';
for (var i = 0; i < s.length; i++) {
    
    
  console.log(s[i]);
}
console.log(i); // 5  i循环结束后,泄露成了全局变量

Block-level scope has been added to ECMAScript 6 (ES6 for short). The block scope is { }included, and ifstatements and forstatements in the statement { }also belong to the block scope.

//1,解决内层变量可能覆盖外层变量的问题
var b = 2;
function fun1(){
    
    
    console.log(b) //2 访问的外层变量
    if(false){
    
    
        let b = 3;//不存在变量提升,变量存在于块级作用域之中。
    }
}
fun1()
//2,解决用来计数的循环变量泄露为全局变量。
var s1 = 'hello';
for (let j = 0; j < s1.length; j++) {
    
    
  console.log(s1[j]); //j存在于块级作用域之中,和其绑定
}
console.log(j); // 报错 j is not defined

5. Can the declared variables be modified?

  • varAnd letcan.
  • constDeclare a read-only constant. Once declared, the value of the constant cannot be changed. constThe declared variable must not change the value, which means that constonce the variable is declared, it must be initialized immediately and cannot be left for later assignment.

const f = 10;
// f= 11;
// console.log(f) //报错 不能进行重复声明

const obj = {
    
    
    name: '小明',
    age: 18
}
obj.age = 20
console.log(obj) //{ name: '小明', age: 20 }  
//const声明常量,不允许对变量重新赋值。对于引用类型的值而言,只要在栈内存保存的地址值不变即可。

===================================================================

es6 destructuring assignment

definition:

The destructuring assignment syntax is a Javascript expression. By destructuring and assigning values, attributes/values ​​can be taken out of the object/array and assigned to other variables.

grammar:


//数组结构
var a, b, rest;
[a, b] = [10, 20];
console.log(a); // 10
console.log(b); // 20

//对象解构
({
    
     a, b } = {
    
     a: 10, b: 20 });
console.log(a); // 10
console.log(b); // 20

// ...rest 解构数组
[a, b, ...rest] = [10, 20, 30, 40, 50];
console.log(a); // 10
console.log(b); // 20
console.log(rest); // [30, 40, 50]

// ...rest 解构对象(最新)
({
    
    a, b, ...rest} = {
    
    a: 10, b: 20, c: 30, d: 40});
console.log(a); // 10
console.log(b); // 20
console.log(rest); // {c: 30, d: 40}

//解析一个从函数返回
function f() {
    
    
  return [1, 2];
}

var a, b; 
[a, b] = f(); 
console.log(a); // 1
console.log(b); // 2

More application scenarios

1. Default value

var a, b;

[a=5, b=7] = [1];
console.log(a); // 1
console.log(b); // 7

2. Exchange variables

var a = 1;
var b = 3;

[a, b] = [b, a];
console.log(a); // 3
console.log(b); // 1

3. Ignore the return value you are not interested in

function f() {
    
    
  return [1, 2, 3];
}

var [a, , b] = f();
console.log(a); // 1
console.log(b); // 3

4. Assign the remaining array to a variable

When deconstructing an array, you can use the remainder mode to assign the remainder of the array to a variable.


var [a, ...b] = [1, 2, 3];
console.log(a); // 1
console.log(b); // [2, 3]

5. Assign a value to the new variable name

You can extract variables from an object and assign them to new variable names that are different from the object attribute names.


var o = {
    
    p: 42, q: true};
var {
    
    p: foo, q: bar} = o;
 
console.log(foo); // 42 
console.log(bar); // true 

6. For of iteration and deconstruction

var people = [
  {
    
    
    name: 'Mike Smith',
    family: {
    
    
      mother: 'Jane Smith',
      father: 'Harry Smith',
      sister: 'Samantha Smith'
    },
    age: 35
  },
  {
    
    
    name: 'Tom Jones',
    family: {
    
    
      mother: 'Norah Jones',
      father: 'Richard Jones',
      brother: 'Howard Jones'
    },
    age: 25
  }
];

for (var {
    
    name: n, family: {
    
    father: f}} of people) {
    
    
  console.log('Name: ' + n + ', Father: ' + f);
}

// "Name: Mike Smith, Father: Harry Smith"
// "Name: Tom Jones, Father: Richard Jones"

Guess you like

Origin blog.csdn.net/WLIULIANBO/article/details/111080723