1. Deconstruct assignment

1. The two most common data structures are Object and Array.

  • Object allows us to create a single entity that stores data items by key.
  • Arrays allow us to collect data items into an ordered list

2. Arrays first

The simplest example

// we have an array with the name and surname
let arr = ["ppx", "ppx1"]

// destructuring assignment
let [firstName, sedname] = arr;

alert(firstName); // ppx
alert(sedname);  // ppx1
Copy the code

2. Two variables are commonly exchanged

let guest = "ppx";
let admin = "ppx1";

// Let's swap the values: make guest=ppx1, admin=ppx
[guest, admin] = [admin, guest]; 
Copy the code

3. The rest of the rest uses three dots to get “rest” “…” :

  • The first two correspond to the first two and the rest goes to REST
let [ppx, ppx1,  ...rest] = ["skt", "clg",  "dk"  , "of the Roman Republic" ,'gen'];
Copy the code
  • Besides,object
  • React {username,userage} = this.props

The basic syntax is:

Let {var1, var2} = {var1:... , var2,... }Copy the code
  • like this one

We have a complex object with many attributes, and we can just extract what we need:

let options = {
  title: "skt",
  sum: 100,
  weight: 200
};

// only extract title as a variable
let { title } = options;

alert(title); // skt
Copy the code
  • What do I do with the rest of these variables?
let {title, ... rest} = options; // Sum and weight are placed in restCopy the code
  • What happens when a function needs to take more than one argument?
function showMe( {title = "what", width = 200, height = 200, others = [] } ) {xxxxx}
Copy the code

A very typical example

1. Fetch the values from the array

let user = { name: "skt", years: 18 };
let {name, years: age, isAdmin = false} = user;
alert( name ); // skt 
alert( age ); // 18 
alert( isAdmin ); // false
Copy the code

2, to sort the content of such objects, how to solve?

  function test(team) {
        let max = 0;
        let maxName = null;
        for (const [name, sore] of Object.entries(team)) {
          if (max < sore) {
            maxName = name;
            max = sore;
          }
        }
        return maxName;
      }

      let team = {
        skt: 500,
        dk: 300,
        gen: 250,
      };

      console.log(test(team));
Copy the code
  • Very nice!

2, Date and time

1. New built-in object: Date. It stores dates, times, and provides date/time management methods

  • We usually use

1. Print the current time

2. Storage time

3. Modify the time

2. Common methods

  • Normally use moment or another formatting time to show the desired formatting

  • The common special method date.now () returns the current timestamp

  • You can convert the time to ms using date.parse (XXX)

Such as:

Let ms = Date. Parse (' 2012-01-26 T13:51:50. 417-07:00); alert(ms); // 1327611110417 (timestamp)Copy the code

3. Actual cases

Create an object for the Date: August 20, 2021, 5:13 am. The time zone is local.

Use the alert.

  • Notice that the months start at 0
//new Date(year, month, date, hour, minute, second, millisecond)
let d1 = new Date(2021, 7, 20, 5, 13);
alert( d1 );
Copy the code

We can also create dates from strings like this:

//new Date(datastring)
let d2 = new Date("February 20, 2012 03:12:00");
alert( d2 );
Copy the code

2, enter a time to return the day of the week?

Date.getday () returns the number of the working day, starting on Sunday

    function getWeek(date) {
      let days = ["SU", "MO", "TU", "WE", "TH", "FR", "SA"];
      return days[date.getDay()];
    }
    let date = new Date(2013, 2, 13);
    alert(getWeek(date));
    alert(d3); // WE
Copy the code

3. How many days ago was the day of a month?

Using this method

If today is the 20th, then getDateAgo(new Date(), 1) should be the 19th and getDateAgo(new Date(), 2) should be the 18th

function getDateBefore(date, days) { date.setDate(date.getDate() - days); return date.getDate(); } let date = new Date(2017, 3, 19); console.log(getDateBefore(date, 1)); / / 18Copy the code

What’s the last day of the month?

function getLastDayOfMonth(year, month) { let date = new Date(year, month + 1, 0); return date.getDate(); } console.log(getLastDayOfMonth(2021, 9)); / / 31Copy the code

5. How to deal with the current time when converted into seconds?

function getSecondsToday() {
      let d = new Date();
      return d.getHours() * 3600 + d.getMinutes() * 60 + d.getSeconds();
    }
    alert(getSecondsToday());
Copy the code

6. How many seconds until tomorrow?

    function getSecondsToTomorrow() {
      let now = new Date();
      let tomorrow = new Date(
        now.getFullYear(),
        now.getMonth(),
        now.getDate() + 1
      );
      let diff = tomorrow - now;
      return Math.round(diff / 1000);
    }
    alert(getSecondsToTomorrow());

Copy the code

3, JSON

1. Why do you need this?

  • Converting an object to a string is cumbersome if you use toString()
let user = { name: "ppx", age: 18, toString() { return `{name: "${this.name}", age: ${this.age}}`; }}; alert(user); // {name: "ppx", age: 18}Copy the code

2. Use json.stringfy –> to convert to a string object

   let user = {
      age: 18,
      name: "ppx",
    };

    console.log(JSON.stringify(user)); // {"age":18,"name":"ppx"}
Copy the code
  • Supported formats

JSON supports the following data types:

  • Object {… }

  • Array […]

  • The original value:

    • String,
    • Numbers,
    • Boolean valuetrue/false.
    • null.
  • Important limitation: No circular references
    //room={xxx} meetup={xx}
    meetup.place = room;       // meetup references room
    room.occupiedBy = meetup; // room references meetup

JSON.stringify(meetup); // Error: Converting circular structure to JSON
Copy the code
  • You can replace the previous object with the parameter replacer
    let user = {
      age: 18,
      name: "ppx",
    };

    console.log(JSON.stringify(user, ["age"])); // {"age":18}
Copy the code
  • Add a format space as an argument

3, JSON parse

1. Grammar:

  • Objective To convert the JSON format to a normal format
let value = JSON.parse(str, [reviver]);
Copy the code

2. Give examples

1, transform array (common)

    // stringified array
    let numbers = "[0, 1, 2, 3]";
    numbers = JSON.parse(numbers);
    console.log(numbers); // (4) [0, 1, 2, 3]
Copy the code

2. Object transfer (common)

Let the userData = '{" name ":" SKT ", "age" : 10, "isAdmin" : false, "friends" :,1,2,3 [0]}'; let user = JSON.parse(userData); console.log(user); // {name: "skt", age: 10, isAdmin: false, friends: Array(4)}Copy the code

3. Note that JSON does not support comments. Add comments to JSON to invalidate it

4. The most common and important things to do are to turn string objects into values

Case of error Cause of error Meetup. date gets a string string does not have a.getDate() method

Let the STR = '{" title ":" SKT ", "date" : "the 2021-08-20 T12:00:00. 000 z"} "; let meetup = JSON.parse(str); alert(meetup.date.getDate()); // Error! meetup.date.getDate is not a functionCopy the code

How to solve this problem?

  • That is to say,Json.parse (XXX,(callback function processing value))
Let the STR = '{" title ":" SKT ", "date" : "the 2021-08-20 T12:00:00. 000 z"} "; let meetup = JSON.parse(str, function (key, value) { if (key == "date") return new Date(value); return value; }); alert(meetup.date.getDate()); / / 20Copy the code