JavaScript basic knowledge learning and quizzes

js learning

1.1 JS calling method and execution sequence

Just add tags anywhere in the HTML page <script type="module"></script>.

Common usage methods include the following:

  • <script type="module"></script>Write JS code directly within the tag.
  • Import the file directly: <script type="module" src="/static/js/index.js"></script>.
  • Introduce the required code into the current scope through the import keyword.

Execution order

  • Similar to HTML and CSS, executed in order from top to bottom;
  • event-driven execution;

Use export in js files to expose variable names and functions

let name = "lsz";
let age = 18;

function print() {
    
    
    console.log("My name is" + name);
}

export {
    
    
    name,
    print
}

Use import in html to import variables and functions exposed in js

    <script type="module">
        import {
      
       name, print } from "/static/js/index.js";
        console.log(name);
        print();

    </script>

1.2 Variables and operators

let and const are used to declare variables, and their scope is the current scope.

let is used to define variables;
const is used to define constants;

Variable type
number: numeric variable, such as 1, 2.5
string: string, such as "acwing", 'yxc', both single and double quotes are acceptable. Each character in the string is read-only.
boolean: Boolean value, such as true, false
object: Object, similar to a pointer in C++, such as [1, 2, 3],{name: "yxc", age: 18},null
undefined: undefined variable
Similar to Python, variable types in JavaScript can change dynamically.

Get the value in the object (dictionary in python, map in cpp)

let d = {
    
    
            name: "lsz",
            age: 18,
        };

console.log(d['name'], d["age"]);
或者是
console.log(d.name, d.age);

js traverses objects using for loop

let d = {
    
    
    name: "lsz",
    age: 18,
};

for (let key in d) {
    
    
    console.log(key);
}

Rounding function parseInt() in js

JS supports bit operations, such as shifting 1 to the left by 10 bits to get 1024

console.log(2 ** 10);
console.log(1 << 10);

The difference between the double equal sign and the triple equal sign: The triple equal sign is strictly equal: it will not judge the numbers represented by strings to be equal to ordinary numbers.

"1" == 1 // true
'1' === 1 // false

1.3 Input and output

enter

  • Input information from the interaction between HTML and the user, such as obtaining the user's keyboard input through input, textarea and other tags, and obtaining the user's mouse input through click, hover and other events.
  • Get input from server side via Ajax and WebSocket
  • standard input

Implementation case: an input box, click the Run button after entering the content, and it can be displayed in the box below.


let input = document.querySelector(".input");
let run = document.querySelector("button");
let output = document.querySelector("pre");

function main() {
    
    
    run.addEventListener("click", function () {
    
    
        let s = input.value;
        output.innerHTML = s;
    });
}


export {
    
    
    main
}

html page

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="/static/css/index.css">
</head>

<body>
    输入:
    <br>
    <textarea class="input" name="" id="" cols="30" rows="10"></textarea>
    <br>
    <button>Run</button>

    <br>
    <pre></pre>

    <script type="module">
        import {
      
       main } from "/static/js/index.js";
        main();
    </script>
</body>

</html>

output

  • Use console.log for debugging, which will output information to the browser console.
  • Change the HTML and CSS of the current page
  • Return results to server via Ajax and WebSocket

Using variables in strings

let name = "lsz", age = 18;
    let s = `My name is ${
      
      name}. I'm  ${
      
      age} years old`;
    console.log(s);

How many decimal places are retained toFixed()

    let x = 1.234567;
    let y = x.toFixed(4);
    console.log(y);
}

Top-up adjustmentMath.ceil()

Round downMath.floor()

Enter two numbers and calculate the sum of the two numbers

Get input:input.value

For outputoutput.innerHTML


let input = document.querySelector(".input");
let run = document.querySelector("button");
let output = document.querySelector("pre");

function main() {
    
    
    run.addEventListener("click", function () {
    
    
        let [a, b] = input.value.split(' ');
        a = parseInt(a), b = parseInt(b);
        output.innerHTML = a + b;

    });

}


export {
    
    
    main
}   

Enter a decimal and return the result rounded toward zero.

function main() {
    
    
    run.addEventListener("click", function () {
    
    
        let x = parseFloat(input.value);
        output.innerHTML = parseInt(x);
    });

}

Input a, b, c, and output the value of (a + b) * c.

function main() {
    
    
    run.addEventListener("click", function () {
    
    
        let [a, b, c] = input.value.split(" ");
        a = parseFloat(a), b = parseFloat(b), c = parseFloat(c);
        output.innerHTML = (a + b) * c;

    });

}

Find the inverse three digit number.

Use division and remainder to find the digits.

function main() {
    
    
    run.addEventListener("click", function () {
    
    
        let x = parseInt(input.value);
        let a = x % 10;
        x = parseInt(x / 10);
        let b = x % 10;
        x = parseInt(x / 10);
        let c = x % 10;
        let s = `${
      
      a}${
      
      b}${
      
      c}`;
        output.innerHTML = s;
    });


}

Output is the following diamond shape.

  *
 ***
*****
 ***
  *

answer

function main() {
    
    
    run.addEventListener("click", function () {
    
    
        let s = "";
        s += "  *\n";
        s += " ***\n";
        s += "*****\n";
        s += " ***\n";
        s += "  *";

        output.innerHTML = s;

    });
}

1.4 Judgment statements

function main() {
    
    
    run.addEventListener("click", function () {
    
    
        let score = parseInt(input.value);
        let res;
        if (score >= 85) {
    
    
            res = "A";
        } else if (score >= 70) {
    
    
            res = "B";
        } else if (score >= 60) {
    
    
            res = "C";
        } else {
    
    
            res = "D";
        }
        output.innerHTML = res;

    });
}

Enter a year, if it is a leap year, output yes, otherwise output no.

Criteria for judging leap years: A full hundred years must be divisible by 400; not a full hundred years, it must be divisible by 4.

function main() {
    
    
    run.addEventListener("click", function () {
    
    
        let year = parseInt(input.value);
        if (year % 100 != 0 && year % 4 === 0 || year % 100 === 0 && year % 400 === 0) {
    
    
            output.innerHTML = "Yes";
        } else {
    
    
            output.innerHTML = "No";
        }

    });
}

Input three numbers and output the maximum of the three numbers.

function main() {
    
    
    run.addEventListener("click", function () {
    
    
        let [a, b, c] = input.value.split(" ");
        a = parseInt(a), b = parseInt(b), c = parseInt(c);
        if (a >= b && a >= c) {
    
    
            output.innerHTML = a;
        } else if (b >= a && b >= c) {
    
    
            output.innerHTML = b;
        } else {
    
    
            output.innerHTML = c;
        }


    });
}

1.5 Loop statement

for loop

for (let i = 0; i < 10; i++) {
    
    
    console.log(i);
}

When enumerating objects or arrays you can use:

The for-in loop can enumerate the subscripts in the array and the keys in the object
. The for-of loop can enumerate the values ​​in the array and the values ​​in the object.

while loop

let i = 0;
while (i < 10) {
    
    
    console.log(i);
    i++;
}

do-while loop

let i = 0;
do {
    
    
    console.log(i);
    i++;
} while (i < 10);

Find the sum of cubes of all numbers from 1 to 100.

function main() {
    
    
    run.addEventListener("click", function () {
    
    
        let sum = 0;
        for (let i = 1; i < 101; i++) {
    
    
            sum += i ** 3;
        }
        console.log(sum);

    });
}

Find the nth term of the Fibonacci sequence. f(1) = 1, f(2) = 1, f(3) = 2, f(n) = f(n-1) + f(n-2).

function main() {
    
    
    run.addEventListener("click", function () {
    
    
        let n = parseInt(input.value);
        let a = 1, b = 1;
        for (let i = 0; i < n - 1; i++) {
    
    
            let c = a + b;
            a = b;
            b = c;
        }
        output.innerHTML = a;
    });
}

Print all prime numbers from 1 to 100.

function main() {
    
    
    run.addEventListener("click", function () {
    
    
        for (let i = 2; i <= 100; i++) {
    
    
            let flag = true;
            for (let j = 2; j * j <= i; j++) {
    
    
                if (i % j == 0) {
    
    
                    flag = false; // 有约数
                    break;
                }
            }
            if (flag) {
    
    
                console.log(i);
            }
        }

    });
}

1.6 Objects

English name: Object. Similar to map in C++, it key:valueconsists of pairs.

value can be a variable, array, object, function, etc.
This in the function definition is used to refer to the "owner" of the function

Object example


let person = {
    
    
    name: "lsz",
    age: 18,
    money: 0,
    friends: ["Bob", "Alice", "Lucy"],
    clothes: {
    
    
        color: "red",
        price: 20,
    },

    add_money: function (x) {
    
    
        this.money += x;
    }
}

function main() {
    
    
    console.log(person);
}

export {
    
    
    main
}

1.7 Array

Arrays are a special kind of objects.
Similar to an array in C++, but the element types in the array can be different.

The elements in the array can be variables, arrays, objects, and functions.

Example

let b = [
    1,
    "lsz",
    [1, 23, 3],
    function () {
    
    
        console.log("hello, world");
    },
    {
    
     name: "lsz", age: 18 }
]

Common properties and functions of arrays

  • Property length: Returns the length of the array. Note that length is an attribute, not a function, so do not add () when calling it.
  • Function push(): Add elements to the end of the array
  • Function pop(): delete the element at the end of the array
  • Function splice(a, b): delete b elements starting from a
  • Function sort(): Sort the entire array from small to large.
    Custom comparison function: array.sort(cmp), the function cmpinputs two elements that need to be compared and returns a real number. A negative number means that the first parameter is smaller than the second parameter, 0 means equal, and a positive number means more than the.

Sort in reverse order

    a.sort(function (a, b) {
    
    
        return b - a;
    });

Or use the reverse function

  a.reverse();

1.8 Functions

Functions are implemented using objects.
Functions are similar to functions in C++.

Three ways to define

function add(a, b) {
    
    
    return a + b;
}

let add = function (a, b) {
    
    
    return a + b;
}

let add = (a, b) => {
    
    
    return a + b;
}

If the return value is not defined, return undefined

1.9 Class

Similar to Class in C++. But there are no private members.

this points to an instance of the class.

father

class Point {
    
    
    constructor(x, y) {
    
     // 构造函数
        this.x = x;
        this.y = y;
    }

    init() {
    
    
        this.sum = this.x + this.y;
    }

    toString() {
    
     //成员函数
        return `(${
      
      this.x}, ${
      
      this.y})`;
    }
}

Subclass

class ColorPoint extends Point {
    
    
    constructor(x, y, color) {
    
    
        super(x, y);  // 表示父类的构造函数
        this.color = color;
    }

    toString() {
    
    
        return `${
      
      this.color} ${
      
      super.toString()}`;
    }
}

The super keyword can be used as either a function or an object.

  • When called as a function, it represents the constructor of the parent class and can only be used in the constructor of the subclass.
  • When super is used as an object, it points to the prototype object of the parent class.

In the constructor of a subclass, the this keyword can be used only after calling super.
When members have the same name, the members of the subclass will overwrite the members of the parent class. Similar to polymorphism in C++.

Static method
Just add the static keyword before the member function. Static methods are not inherited by instances of the class and can only be called through the class.

1.10 Event

acwing event handout address: https://www.acwing.com/blog/content/18189/

JavaScript code is generally triggered through events.

addEventListenerYou can bind event triggering functions to elements through functions.

Mouse
click: left mouse button click
dblclick: left mouse button double click
contextmenu: right mouse button click
mousedown: mouse press, including left button, scroll wheel, right button
event.button: 0 means left button, 1 means middle button, 2 means right button
mouseup: The mouse bounces up, including left button, scroll wheel, and right button
event.button: 0 means left button, 1 means middle button, and 2 means right button.

Click event example

let div = document.querySelector("div");

function main() {
    
    
    div.addEventListener("click", function (event) {
    
    
        console.log(event.type);
    });
}

export {
    
    
    main
}

Keyboard
keydown: Whether a certain key is pressed, the event will be triggered continuously
. event.code: Returns which key was pressed
. event.altKey, event.ctrlKey, and event.shiftKey respectively indicate whether the alt, ctrl, and shift keys were pressed at the same time.

keyup: whether a key is released
. Common attributes of the event are the same as above
. keypress: triggered immediately after the keydown event, and only triggered when a character key is pressed. Suitable for determining characters entered by the user.
Common attributes of event are the same as above

exercise

part 1

1 Input two integers and find the sum of these two integers.

let buf = "";

process.stdin.on("readable", function() {
    
    
    let chunk = process.stdin.read(); //缓存,读入能够读的内容,byte类型
    if (chunk) buf += chunk.toString(); 
});

process.stdin.on("end", function() {
    
     //读完的时候
   let [a, b] = buf.split(" ").map(function(x) {
    
    
       return parseInt(x);
   }); // map(x => {return parseInt(x)})
   
   console.log(a + b);
});

2 Read four integers A, B, C, DA, B, C, D, and calculate the value of (A×B−C×D).

To read new lines, use split(“\n”).

let buf = "";

process.stdin.on("readable", function() {
    
    
  let chunk = process.stdin.read();
  if (chunk) buf += chunk.toString();
})

process.stdin.on("end", function() {
    
    
    let [a, b, c, d] = buf.split("\n").map(x => {
    
    return parseInt(x)});//转变成整数
    console.log("DIFERENCA = " + (a * b - c * d));
})

3 Given two points P1 and P2, where the coordinates of P1 are (x1, y1) and the coordinates of P2P2 are (x2, y2), please calculate the distance between the two points.
distance = ( x 2 − x 1 ) 2 + ( y 2 − y 1 ) 2 distance=\sqrt{(x2−x1)^2+(y2−y1)^2}distance=( x 2x 1 )2+( y2 _y 1 )2
Input format

There are two lines of input, each line contains two double-precision floating point numbers xi, yixi, yi, representing the coordinates of one of the points.

Enter values ​​to one decimal place.

Output format

Print your results to four decimal places.

Question link: https://www.acwing.com/problem/content/618/

Solution: To fix a few decimal places, use toFixed (how many decimal places) syntax


let buf = "";

process.stdin.on("readable", function(){
    
    
   let chunk = process.stdin.read();
   if (chunk) buf += chunk.toString();
});

process.stdin.on("end", function() {
    
    
    let lines = buf.split("\n"); //先通过\n 分成2行
    // 分别读入每一行的数字
    let [x1, y1] = lines[0].split(" ").map(x => {
    
    return parseFloat(x)});
    let [x2, y2] = lines[1].split(" ").map(x => {
    
    return parseFloat(x)});
    
    let dx = x1 - x2;
    let dy = y1 - y2;
    console.log(Math.sqrt(dx * dx + dy * dy).toFixed(4));
});
  1. banknote

Question link: https://www.acwing.com/problem/content/655/

Question meaning: Read an integer value and decompose it into the sum of multiple banknotes. Multiple banknotes of each denomination can be used, and the number of banknotes used is required to be as small as possible.

Solution: Greedy. Do it greedily from the largest face value to the smallest face value.

let buf = "";

process.stdin.on("readable", function() {
    
    
   let chunk = process.stdin.read();
   if (chunk) buf += chunk.toString();
});

process.stdin.on("end", function() {
    
    
    let n = parseInt(buf);
    
    let money = [100, 50, 20, 10, 5, 2, 1];
    console.log(n);
    
    for (let p of money) {
    
    
        let cnt = parseInt(n / p); // 下取整,用parseInt
        console.log(`${
      
      cnt} nota(s) de R$ ${
      
      p},00`);
        n %= p; // 等于 n - cnt * p
    }
    
});

Learning: Use output variables ${}, for of loop to traverse the values ​​of the array, and use the parseInt function to round down.

  1. Time conversion

Question link: https://www.acwing.com/problem/content/656/

Question: Read an integer value, which is the duration (in seconds) of an event in the factory. Please convert it to hours: minutes: seconds.

ac code

let buf = "";

process.stdin.on("readable", function() {
    
    
   let chunk = process.stdin.read();
   if (chunk) buf += chunk.toString();
});

process.stdin.on("end", function() {
    
    
    let x = parseInt(buf);
    let hours = parseInt(x / 3600);
    x %= 3600;
    let minutes = parseInt(x / 60);
    x %= 60;
    let seconds = x;
    console.log(`${
      
      hours}:${
      
      minutes}:${
      
      seconds}`);
    
});
  1. multiple

Question meaning: Read two positive integer values ​​A and B.

If one is an integer multiple of the other, output it Sao Multiplos, otherwise output it Nao sao Multiplos.

ac code

let buf = "";

process.stdin.on("readable", function(){
    
    
    let chunk = process.stdin.read();
    if (chunk) buf += chunk.toString();
});

process.stdin.on("end", function() {
    
    
    let [a, b] = buf.split(" ").map(x => {
    
    return parseInt(x)});
    if ( a % b == 0 || b % a == 0) {
    
    
        console.log("Sao Multiplos");
    } else {
    
    
        console.log("Nao sao Multiplos");
    }
});
  1. snack

Question link: https://www.acwing.com/problem/content/description/662/

Given the number and quantity of a certain snack, please calculate the total value.


let buf = "";

process.stdin.on("readable", function() {
    
    
   let chunk = process.stdin.read();
   if (chunk) buf += chunk.toString();
});

process.stdin.on("end", function() {
    
    
    let [a, b] = buf.split(" ").map(x => {
    
    return parseInt(x)});
    let food = [4, 4.5, 5, 2, 1.5];
    let money = food[a - 1] * b;
    console.log(`Total: R$ ${
      
      money.toFixed(2)}`);
    
});
  1. interval

Question link: https://www.acwing.com/problem/content/661/

let buf = "";

process.stdin.on("readable", function() {
    
    
    let chunk = process.stdin.read();
    if (chunk) buf += chunk.toString();
});

process.stdin.on("end", function() {
    
    
   let x = parseFloat(buf);
   if (x < 0 || x > 100) console.log("Fora de intervalo");
   
   if (x >= 0 && x <= 25) console.log("Intervalo [0,25]");
   else if (x > 25 && x <= 50) console.log("Intervalo (25,50]");
   else if (x > 50 && x <= 75) console.log("Intervalo (50,75]");
   else if (x > 75 && x <= 100)  console.log("Intervalo (75,100]");
});
  1. game time

Question link: https://www.acwing.com/problem/content/669/

let buf = "";

process.stdin.on("readable", function() {
    
    
   let chunk = process.stdin.read();
   if (chunk) buf += chunk.toString();
});

process.stdin.on("end", function() {
    
    
   let [x, y] = buf.split(" ").map(x => {
    
    return parseInt(x)}); 
   let res;
   if (x == y) res = 24;
   else if (y > x) res = y - x;
   else {
    
    
       res = 24 - x + y;
   }
   console.log(`O JOGO DUROU ${
      
      res} HORA(S)`);
});
  1. animal

Question link: https://www.acwing.com/problem/content/672/

Idea: Take the first letter of each word and splice them together as a label for each animal. This can save a lot of time in writing words.

let buf = "";

process.stdin.on("readable", function() {
    
    
   let chunk = process.stdin.read();
   if (chunk) buf = chunk.toString();
});

process.stdin.on("end", function() {
    
    
    let [a, b, c] = buf.split("\n");
    x = a[0] + b[0] + c[0];
    // console.log("x: " + x);
    let name;
    if ( x == "vac") name = "aguia";
    else if ( x == "vao") name = "pomba";
    else if (x == "vmo") name = "homem";
    else if (x == "vmh") name = "vaca";
    else if (x == "iih" && c == "hematofago") name = "pulga";
    else if (x == "iih" && c == "herbivoro") name = "lagarta";
    else if (x == "iah")  name = "sanguessuga";
    else if (x == "iao") name = "minhoca";
    
    console.log(name);
});

  1. even

Question link: https://www.acwing.com/problem/content/710/

Question meaning: Output even numbers.



for (let i = 1; i <= 100; i ++) {
    
    
    if ( i % 2 == 0)
        console.log(i);
}

  1. A positive number

Question link: https://www.acwing.com/problem/content/714/

Enter 6 real numbers, they are either positive or negative. Please count and output the number of positive numbers.

let buf = "";

process.stdin.on("readable", function() {
    
    
    let chunk = process.stdin.read();
    if (chunk) buf += chunk.toString();
});


process.stdin.on("end", function() {
    
    
    let num = buf.split("\n").map(x => {
    
    return parseFloat(x)}); // 转换成浮点数存入num中
    let n = 0;
    for (let i of num) {
    
    
        if (i > 0) n ++;
    }
    
    console.log(`${
      
      n} positive numbers`)
}); 

Learn: for of loop

  1. Increasing sequence

Question link: https://www.acwing.com/problem/content/723/

Question meaning: Output 1, 2, 3,... until x itself.

let buf = "";

process.stdin.on("readable", function(){
    
    
    let chunk = process.stdin.read();
    if (chunk) buf += chunk.toString();
});

process.stdin.on("end", function() {
    
    
    let num = buf.split("\n").map(x => {
    
    return parseInt(x)});
    for (let i of num) {
    
    
        if (i === 0) break;
        let line = "";
        
        for (let j = 1; j <= i; j ++) {
    
    
            line += `${
      
      j} `;
        }
        console.log(line);
    }
})


Learning: You cannot use console.log to output directly because it contains line breaks. Use a string transition to output a whole line.

  1. Divisor

Question link: https://www.acwing.com/problem/content/726/

Question: Find the divisor

let buf = "";

process.stdin.on("readable", function() {
    
    
    let chunk = process.stdin.read();
    if (chunk) buf += chunk.toString();
});

process.stdin.on("end", function(){
    
    
    let x = parseInt(buf);
    for (let i = 1; i <= x; i ++) {
    
    
        if (x % i == 0)
            console.log(i);
    }
});
  1. diamond

Question link: https://www.acwing.com/problem/content/729/

Question: Draw a rhombus in a square.

Manhattan distance
distance = abs ( x 1 − x 2 ) + abs ( y 1 − y 2 ) distance = abs(x_1 - x_2) + abs(y_1 - y_2)distance=abs(x1x2)+abs(y1y2)

Cut out a rhombus from a square: the Manhattan distance from the four sides of the rhombus to the center is n/2 (the coordinates of the center point, represented by m in the code below). All places to the center less than n/2 are assigned asterisks, and other places are assigned as spaces.

let buf = "";

process.stdin.on("readable", function(){
    
    
    let chunk = process.stdin.read();
    if (chunk) buf += chunk.toString();
});

process.stdin.on("end", function(){
    
    
    let n = parseInt(buf);
    let m = parseInt(n / 2); // 中心点的坐标(m, m)
    
    for (let i = 0; i < n; i ++) {
    
    
        let line = "";
        for (let j = 0; j < n; j ++) {
    
    
            if (Math.abs(i - m) + Math.abs(j - m) <= m)
                line += "*";
            else line += " ";
        }
        console.log(line);
    }
});

part 2

  1. Array replacement

Question link: https://www.acwing.com/problem/content/739/

Question meaning: Replace the numbers less than or equal to 0 in the array

let buf = "";

process.stdin.on("readable", function() {
    
    
   let chunk = process.stdin.read();
   if (chunk) buf += chunk.toString();
});

process.stdin.on("end", function() {
    
    
   let xs = buf.split("\n").map( x => {
    
    return parseInt(x)});
   for (let i = 0; i < 10; i++) {
    
    
       if ( xs[i] <= 0) {
    
    
           console.log(`X[${
      
      i}] = 1`);
       }
       else console.log(`X[${
      
      i}] = ${
      
      xs[i]}`);
   }
});

\743. Rows in array

Question link: https://www.acwing.com/problem/content/745/

Input a two-dimensional array M[12][12], and according to the input requirements, find the average value or the sum of the elements in a certain row of the two-dimensional array.


let buf = "";

process.stdin.on("readable", function() {
    
    
   let chunk = process.stdin.read();
   if (chunk) buf += chunk.toString();
});

process.stdin.on("end", function(){
    
    
    let lines = buf.split("\n");
    // console.log(lines);
    
    let l = parseInt(lines[0]);
    let c = lines[1]; 
    
    let d = [];
    for (let i = 0; i < 12; i++) {
    
    
        d.push(lines[i + 2].split(" ").map(x => {
    
    return parseFloat(x)}));
    }
    // console.log(d);
    
    let sum  = 0;
    for (let i = 0; i < 12; i ++) {
    
    
        sum += d[l][i];
    }
    
    if ( c == "M") sum /= 12;
    
    console.log(sum.toFixed(1));
});

Acquire

Use JS to parse two-dimensional arrays and use the push method

let d = [];
for (let i = 0; i < 12; i++) {
    
    
    d.push(lines[i + 2].split(" ").map(x => {
    
    return parseFloat(x)}));
}

\753. Square matrix I

Question link: https://www.acwing.com/problem/content/755/

Idea: The minimum value to the upper, lower, left and right boundaries is the value of each position

let buf = "";

process.stdin.on("readable", function() {
    
    
   let chunk = process.stdin.read();
   if (chunk) buf += chunk.toString();
});

process.stdin.on("end", function(){
    
     
    let ns = buf.split("\n").map(x => {
    
    return parseInt(x)});
    for (let n of ns) {
    
    
        if ( n == 0) break;
        for (let i = 0; i < n; i ++) {
    
    
            let line = "";
            for (let j = 0; j < n; j ++) {
    
    
                line += `${
      
      Math.min(i + 1, n - i, j + 1, n - j)} `;
            }
            console.log(line);
        }
        
        console.log();
    }
    
}); 

\747. The upper left half of the array

Input a two-dimensional array M[12][12], and according to the input requirements, find the average value or the sum of the elements in the upper left half of the two-dimensional array.

j in row i is 10 - i

let buf = "";
process.stdin.on("readable", function() {
    
    
    let chunk = process.stdin.read();
    if (chunk) buf += chunk.toString();
});

process.stdin.on("end", function() {
    
    
    let n = buf.split("\n");
    let c = n[0];
    let d = [];
    for (let i = 0; i < 12; i ++) {
    
    
        d.push(n[i + 1].split(" ").map(x => {
    
    return parseFloat(x)}));
    }
    // console.log(d);
    let sum = 0;
    let cnt = 0;
    
    for (let i = 0; i < 12; i ++) {
    
    
        for (let j = 0; j <= 10 - i; j ++) {
    
    
            sum += d[i][j];
            cnt ++;
        }
    }
    
    if (c == "M") sum /= cnt;
    
    console.log(sum.toFixed(1));
})

\756. Snake matrix

Input two integers n and m, output a matrix with n rows and m columns, and fill the matrix with numbers 1 to n×m in a serpentine shape.

undone

\760. String length

Given a non-empty string whose length does not exceed 100, please find its specific length.

let buf = "";
process.stdin.on("readable", function() {
    
    
    let chunk = process.stdin.read();
    if (chunk) buf += chunk.toString();
});

process.stdin.on("end", function() {
    
    

    console.log(buf.length);
})

\772. Characters that appear only once

Question link: https://www.acwing.com/problem/content/774/

Please determine whether there are characters that appear only once in the string.

let buf = "";

process.stdin.on("readable", function(){
    
    
   let chunk = process.stdin.read();
   if (chunk) buf += chunk.toString();
});


process.stdin.on("end", function(){
    
    
    let cnt = {
    
    };
    let str = buf.split("\n")[0];  // 去掉行末回车
    for (let c of str) {
    
    
        if (c in cnt) cnt[c] ++;
        else cnt[c] = 1;
    }
    
    for (let c of str) {
    
    
        if (cnt[c] == 1) {
    
    
            console.log(c);
            return;
        }
    }
    
    console.log("no");
    
});

\770. Word replacement

Question link: https://www.acwing.com/problem/content/772/

You need to replace one of the words with another word and output the replaced string.

let buf = "";

process.stdin.on("readable", function(){
    
    
   let chunk = process.stdin.read();
   if (chunk) buf += chunk.toString();
});


process.stdin.on("end", function(){
    
    
    let res = "";
    let [str, a, b] = buf.split("\n"); //每行分开
    let words = str.split(" "); // 按照空格分开成字符串
    
    for (let w of words) {
    
    
        if (w === a) res += b + " ";
        else res += w + " ";
    }
    
    console.log(res);
    
});
  1. inverted words

Question link: https://www.acwing.com/problem/content/777/

Output words in reverse order

let buf = "";

process.stdin.on("readable", function(){
    
    
   let chunk = process.stdin.read();
   if (chunk) buf += chunk.toString();
});


process.stdin.on("end", function(){
    
    
   let words = buf.split("\n")[0];
   words = words.split(" ");
   words.reverse();
   let res = "";
   for (w of words) res += w + " ";
   console.log(res);

});

  1. Maximum value of x and y

Question link: https://www.acwing.com/problem/content/807/

Input two integers x and y, please write a function, int max(int x, int y), to calculate and output the maximum value of x and y.

let buf = "";

process.stdin.on("readable", function(){
    
    
    let chunk = process.stdin.read();
    if (chunk) buf += chunk.toString();
});

process.stdin.on("end", function() {
    
    
   let [a, b] = buf.split(" ").map(x => {
    
    return parseInt(x)});
   console.log( a < b ? b: a);
});

JS common library functions

1.11.1 jQuery

Get a certain label on the front end, bind events, etc.

selector, get tag

function main() {
    
    
    let div = document.querySelector("div"); // 选择div标签
    console.log(div);

    let $div = $("div"); // 选择div标签,jquery写法
    console.log($div);
}

Bind action

function main() {
    
    
    let $div = $("div");
    $div.on("click", function () {
    
    
        console.log("click div");
    })
}


hide and show

html

<body>
    <script type="module">
        import {
      
       main } from "/static/js/index.js";

        main();
    </script>

    <div></div>
    <button id="hide-btn">隐藏</button>
    <button id="show-btn">展现</button>
</body>

js file hide and show

function main() {
    
    
    let $div = $("div");
    let $btn_hide = $("#hide-btn");
    let $btn_show = $("#show-btn");

    $btn_hide.click(function () {
    
    
        $div.hide();
    });

    $btn_show.click(function () {
    
    
        $div.show();
    });
}

export {
    
    
    main
}


Operations on classes: addClass and removeClass

function main() {
    
    
    let $div = $("div");
    let $btn_hide = $("#hide-btn");
    let $btn_show = $("#show-btn");

    $div.click(function () {
    
     //单击添加my-div类
        $div.addClass('my-div');
    });

    $div.dblclick(function () {
    
     //双击消除my-div类
        $div.removeClass('my-div');
    });
}

export {
    
    
    main
}

For direct operation of css

    $div.click(function () {
    
    
        console.log($div.css('background-color'));
        $div.css({
    
    
            width: "200px",
            height: "200px",
            "background-color": "orange"
        });
    });

Get properties

$div.attr('id')

ajax get and post methods

$.ajax({
    
    
    url: url,
    type: "GET",
    data: {
    
    
    },
    dataType: "json",
    success: function (resp) {
    
    

    },
});

$.ajax({
    
    
    url: url,
    type: "POST",
    data: {
    
    
    },
    dataType: "json",
    success: function (resp) {
    
    

    },
});

1.11.2 setTimeout and setInterval

setTimeout delays execution in milliseconds.

function main() {
    
    
    let $div = $("div");
    $div.click(function () {
    
    
        setTimeout(() => {
    
    
            console.log("hhhhh");
        }, 2000);
    });
}

setInterval delays the execution of the loop in milliseconds

function main() {
    
    
    let $div = $("div");

    let func_id;

    $div.click(function () {
    
    
        if (func_id) return false;

        func_id = setInterval(() => {
    
    
            console.log("hhhhh");
        }, 500);
    });

    $div.dblclick(function () {
    
    
        clearInterval(func_id);
    });
}

1.11.3 requestAnimationFrame

requestAnimationFrame(func)
This function will be executed once before the browser refreshes the page next time. It is usually written recursively to execute the func function 60 times per second. When calling, a parameter will be passed in, indicating the timestamp of function execution, in milliseconds.

function main() {
    
     // 每帧将div的宽度增加1像素
    let step = () => {
    
    
        $("div").width($("div").width() + 1);
        requestAnimationFrame(step);
    };
    requestAnimationFrame(step);
}

Click to cancel the animation effect

function main() {
    
    
    let func_id;

    let step = (timestep) => {
    
    
        $("div").width($("div").width() + 0.025);
        requestAnimationFrame(step);

        if (timestep / 1000 <= 10) {
    
    
            func_id = requestAnimationFrame(step);
        }
    };

    func_id = requestAnimationFrame(step);

    $("div").click(function () {
    
    
        cancelAnimationFrame(func_id);
    });
}


export {
    
    
    main
}


1.11.4 Map and Set

Map

Map objects hold key-value pairs.

Use for...of or forEach to traverse in insertion order.
Key values ​​can be any value, including functions, objects, or any primitive type.

Commonly used APIs:

set(key, value): Insert a key-value pair. If the key already exists, the original value will be overwritten.
get(key): Find the keyword. If it does not exist, return undefined.
Size: Return the number of key-value pairs
has(key) : Returns whether the keyword key is included
delete(key): Delete the keyword key
clear(): Delete all elements

function main() {
    
    
    let map = new Map();
    map.set("name", "lsz");
    map.set("age", 18);
    
    // 遍历输出
    for (let [key, value] of map) {
    
    
        console.log(key, value);
    }
	// 第二种遍历,使用forEach
    map.forEach(function (key, value) {
    
    
        console.log(key, value);
    })
}

Set

Set objects allow you to store unique values ​​of any type, whether primitive values ​​or object references.

Use for...of or forEach to traverse in insertion order.
Commonly used APIs:

add(): Add an element
has(): Return whether a certain element is included
size: Return the number of elements
delete(): Delete an element
clear(): Delete all elements

   let set = new Set();

    set.add("lsz");
    set.add(function () {
    
    
        console.log("hello");
    });
    set.add(18);

    console.log(set);
    set.delete(18);
    console.log(set.size);

1.11.5 localStorage

Key-value pairs can be stored on the user's browser.

Commonly used APIs:

setItem(key, value): Insert
getItem(key): Find
removeItem(key): Delete
clear(): Clear

function main() {
    
    
    localStorage.setItem("name", "lsz");
    console.log(localStorage.getItem("name"));
}

1.11.6 JSON

JSON objects are used to serialize objects, arrays, numbers, strings, Boolean values, and null.

Commonly used APIs:

JSON.parse(): Parse strings into objects
JSON.stringify(): Convert objects into strings

    let obj = {
    
    
        name: "Lsz",
        age: 18,
    };

    let str = JSON.stringify(obj);

    let new_obj = JSON.parse(str);
    console.log(typeof new_obj);

1.11.7 Date

API that returns an integer, the value is the number of milliseconds that have elapsed from 1970-1-1 00:00:00 UTC (Universal Standard Time) to a certain moment:

APIs related to instances of Date objects:

new Date(): Returns the current time.
new Date("2022-04-15T15:30:00.000+08:00"): Returns the time at 15:30:00 on April 15, 2022, Beijing time.
The difference between two Date object instances is the number of milliseconds.
getDay(): Returns the day of the week, 0 represents Sunday, and 1-6 represents Monday to Saturday.
getDate(): Returns the day, with a value of 1-31.
getMonth(): Returns the month, with a value. is 0-11
getFullYear(): Returns the year
getHours(): Returns the hours
getMinutes(): Returns the minutes
getSeconds(): Returns the seconds
getMilliseconds(): Returns the milliseconds

1.11.8 WebSocket

Establish a full-duplex connection to the server.

Commonly used APIs:

new WebSocket('ws://localhost:8080');: Establish ws connection.
send(): Send a string to the server. Generally, JSON is used to serialize the incoming object into a string.
onopen: similar to onclick, triggered when the connection is established.
onmessage: Triggered when a message is received from the server.
close(): Close the connection.
onclose: Triggered when the connection is closed.

1.11.9 window

window.open("https://www.acwing.com") opens the page in a new tab bar.
location.reload() refreshes the page.
location.href = "https://www.acwing.com": Open the page in the current tab bar.

function main() {
    
    
    $("div").css("cursor", "pointer");
    $("div").click(() => {
    
    
        window.open("https://www.acwing.com");
    })
}

Canvas Tutorial

https://developer.mozilla.org/zh-CN/docs/Web/API/Canvas_API/Tutorial

other

Source: Acwing

Guess you like

Origin blog.csdn.net/shizheng_Li/article/details/128505024