JavaScript基础知识学习与刷题

js学习

1.1 JS的调用方式与执行顺序

HTML页面中的任意位置加上<script type="module"></script>标签即可。

常见使用方式有以下几种:

  • 直接在<script type="module"></script>标签内写JS代码。
  • 直接引入文件:<script type="module" src="/static/js/index.js"></script>
  • 将所需的代码通过import关键字引入到当前作用域。

执行顺序

  • 类似于HTML与CSS,按从上到下的顺序执行;
  • 事件驱动执行;

js文件中使用export暴露出来变量名和函数

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

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

export {
    
    
    name,
    print
}

html中使用import导入进来js中暴露出来的变量和函数

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

    </script>

1.2 变量与运算符

let与const 用来声明变量,作用范围为当前作用域。

let用来定义变量;
const用来定义常量;

变量类型
number:数值变量,例如1, 2.5
string:字符串,例如"acwing", ‘yxc’,单引号与双引号均可。字符串中的每个字符为只读类型。
boolean:布尔值,例如true, false
object:对象,类似于C++中的指针,例如[1, 2, 3],{name: "yxc", age: 18},null
undefined:未定义的变量
类似于Python,JavaScript中的变量类型可以动态变化。

取出对象(python中的字典,cpp中的map)里面的值

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

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

js遍历对象,使用for循环

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

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

js中取整函数parseInt()

js中支持位运算,比如1左移10位,得到1024

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

双等号和三等号的区别:三等号是严格等于:不会把字符串表示的数字和一般的数字判别相等

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

1.3 输入与输出

输入

  • 从HTML与用户的交互中输入信息,例如通过input、textarea等标签获取用户的键盘输入,通过click、hover等事件获取用户的鼠标输入。
  • 通过Ajax与WebSocket从服务器端获取输入
  • 标准输入

实现案例:一个输入框,输入内容后点击Run按钮,可以在下方的框中显示。


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页面

<!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>

输出

  • 调试用console.log,会将信息输出到浏览器控制台
  • 改变当前页面的HTML与CSS
  • 通过Ajax与WebSocket将结果返回到服务器

字符串中使用变量

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

保留几位小数 toFixed()

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

上取整 Math.ceil()

下取整Math.floor()

输入两个数,计算两个数的和

获取输入:input.value

输出用output.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
}   

输入一个小数,返回向零取整之后的结果。

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

}

输入a, b, c,输出 (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;

    });

}

求反三位数。

使用除法和取余得到各位数。

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;
    });


}

输出如下的菱形。

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

解答

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

        output.innerHTML = s;

    });
}

1.4 判断语句

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;

    });
}

输入一个年份,如果是闰年输出yes,否则输出no。

判断闰年的准则:整百年,需要被400整除;不是整百年,需要被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";
        }

    });
}

输入三个数,输出三个数中的最大值。

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 循环语句

for循环

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

枚举对象或数组时可以使用:

for-in循环,可以枚举数组中的下标,以及对象中的key
for-of循环,可以枚举数组中的值,以及对象中的value

while循环

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

do-while循环

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

求1~100中所有数的立方和。

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

    });
}

求斐波那契数列的第n项。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;
    });
}

打印1~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 对象

英文名称:Object。 类似于C++中的map,由key:value对构成。

value可以是变量、数组、对象、函数等。
函数定义中的this用来引用该函数的“拥有者”

对象举例


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 数组

数组是一种特殊的对象。
类似于C++中的数组,但是数组中的元素类型可以不同。

数组中的元素可以是变量、数组、对象、函数。

举例

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

数组的常用属性和函数

  • 属性length:返回数组长度。注意length是属性,不是函数,因此调用的时候不要加()
  • 函数push():向数组末尾添加元素
  • 函数pop():删除数组末尾的元素
  • 函数splice(a, b):删除从a开始的b个元素
  • 函数sort():将整个数组从小到大排序
    自定义比较函数:array.sort(cmp),函数cmp输入两个需要比较的元素,返回一个实数,负数表示第一个参数小于第二个参数,0表示相等,正数表示大于。

逆序排序

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

或者使用reverse函数

  a.reverse();

1.8 函数

函数是用对象来实现的。
函数也C++中的函数类似。

三种定义方式

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

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

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

如果未定义返回值,则返回undefined

1.9 类

与C++中的Class类似。但是不存在私有成员。

this指向类的实例。

父类

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

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

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

子类

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

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

super这个关键字,既可以当作函数使用,也可以当作对象使用。

  • 作为函数调用时,代表父类的构造函数,且只能用在子类的构造函数之中。
  • super作为对象时,指向父类的原型对象。

在子类的构造函数中,只有调用super之后,才可以使用this关键字。
成员重名时,子类的成员会覆盖父类的成员。类似于C++中的多态。

静态方法
在成员函数前添加static关键字即可。静态方法不会被类的实例继承,只能通过类来调用。

1.10 事件

acwing事件讲义地址:https://www.acwing.com/blog/content/18189/

JavaScript的代码一般通过事件触发。

可以通过addEventListener函数为元素绑定事件的触发函数。

鼠标
click:鼠标左键点击
dblclick:鼠标左键双击
contextmenu:鼠标右键点击
mousedown:鼠标按下,包括左键、滚轮、右键
event.button:0表示左键,1表示中键,2表示右键
mouseup:鼠标弹起,包括左键、滚轮、右键
event.button:0表示左键,1表示中键,2表示右键

点击事件举例

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

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

export {
    
    
    main
}

键盘
keydown:某个键是否被按住,事件会连续触发
event.code:返回按的是哪个键
event.altKey、event.ctrlKey、event.shiftKey分别表示是否同时按下了alt、ctrl、shift键。

keyup:某个按键是否被释放
event常用属性同上
keypress:紧跟在keydown事件后触发,只有按下字符键时触发。适用于判定用户输入的字符。
event常用属性同上

习题

part 1

1 输入两个整数,求这两个整数的和是多少。

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 读取四个整数 A,B,C,DA,B,C,D,并计算 (A×B−C×D) 的值。

换行读入,使用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 给定两个点 P1和 P2,其中 P1 的坐标为 (x1,y1),P2P2 的坐标为 (x2,y2),请你计算两点间的距离是多少。
d i s t a n c e = ( x 2 − x 1 ) 2 + ( y 2 − y 1 ) 2 distance=\sqrt{(x2−x1)^2+(y2−y1)^2} distance=(x2x1)2+(y2y1)2
输入格式

输入共两行,每行包含两个双精度浮点数 xi,yixi,yi,表示其中一个点的坐标。

输入数值均保留一位小数。

输出格式

输出你的结果,保留四位小数。

题目链接:https://www.acwing.com/problem/content/618/

题解:固定几位小数,使用toFixed(几位数)语法


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. 钞票

题目链接:https://www.acwing.com/problem/content/655/

题意:读取一个整数值并将其分解为多张钞票的和,每种面值的钞票可以使用多张,并要求所用的钞票数量尽可能少。

题解:贪心。从最大面值向最小面值贪心来做。

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
    }
    
});

习得: 输出变量使用${}, for of循环遍历数组的值,下取整使用parseInt函数。

  1. 时间转换

题目链接:https://www.acwing.com/problem/content/656/

题意:读取一个整数值,它是工厂中某个事件的持续时间(以秒为单位),请你将其转换为小时:分钟:秒来表示。

ac代码

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. 倍数

题意:读取两个正整数值 A和 B。

如果其中一个是另一个的整数倍,则输出 Sao Multiplos,否则输出 Nao sao Multiplos

ac代码

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. 零食

题目链接:https://www.acwing.com/problem/content/description/662/

在给定某种零食的编号和数量,请你计算总价值是多少。


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. 区间

题目链接: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. 游戏时间

题目链接: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. 动物

题目链接:https://www.acwing.com/problem/content/672/

思路:取出每个单词的首字母,然后拼接在一起,作为每个动物的标签,这样可以节省很多写单词的时间。

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. 偶数

题目链接:https://www.acwing.com/problem/content/710/

题意:输出偶数。



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

  1. 正数

题目链接:https://www.acwing.com/problem/content/714/

输入 6个实数,它们要么是正数,要么是负数。请你统计并输出正数的个数。

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`)
}); 

习得:for of 循环

  1. 递增序列

题目链接:https://www.acwing.com/problem/content/723/

题意:输出1,2,3,… 直到 x自己。

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);
    }
})


习得:不能用console.log直接输出,因为它带换行。使用字符串过渡一下,即可输出一整行。

  1. 约数

题目链接:https://www.acwing.com/problem/content/726/

题意:求约数

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. 菱形

题目链接: https://www.acwing.com/problem/content/729/

题意:在正方形中绘制菱形。

曼哈顿距离
d i s t a n c e = a b s ( x 1 − x 2 ) + a b s ( y 1 − y 2 ) distance = abs(x_1 - x_2) + abs(y_1 - y_2) distance=abs(x1x2)+abs(y1y2)

一个正方形中抠出一个菱形:菱形四周到中心的曼哈顿距离都是 n/2(中心点的坐标,下面代码中用m表示)。所有到中心小于n/2 的地方赋值成星号,其他地方赋值成空格。

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. 数组替换

题目链接:https://www.acwing.com/problem/content/739/

题意:替换数组中小于等于0的数

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. 数组中的行

题目链接:https://www.acwing.com/problem/content/745/

输入一个二维数组 M[12][12],根据输入的要求,求出二维数组中某一行的元素的平均值或元素的和。


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));
});

习得

用JS解析二维数组,使用push方法

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

\753. 平方矩阵 I

题目链接:https://www.acwing.com/problem/content/755/

思路:到上下左右边界的最小值,就是每个位置的值

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. 数组的左上半部分

输入一个二维数组 M[12][12],根据输入的要求,求出二维数组的左上半部分元素的平均值或元素的和。

第i行的j是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. 蛇形矩阵

输入两个整数 n 和 m,输出一个 n 行 m 列的矩阵,将数字 1到 n×m按照回字蛇形填充至矩阵中。

undone

\760. 字符串长度

给定一行长度不超过100 的非空字符串,请你求出它的具体长度。

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. 只出现一次的字符

题目链接:https://www.acwing.com/problem/content/774/

请你判断是否存在只在字符串中出现过一次的字符。

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. 单词替换

题目链接: https://www.acwing.com/problem/content/772/

需要将其中的某个单词替换成另一个单词,并输出替换之后的字符串。

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. 倒排单词

题目链接:https://www.acwing.com/problem/content/777/

逆序输出单词

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. x和y的最大值

题目链接:https://www.acwing.com/problem/content/807/

输入两个整数 x和 y,请你编写一个函数,int max(int x, int y),计算并输出 x 和 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常用库函数

1.11.1 jQuery

获取前端的某个标签,绑定事件等。

选择器,获取标签

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

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

绑定动作

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


隐藏和展现

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文件 hide 和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
}


对类的操作:addClass和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
}

对于css直接操作

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

获取属性

$div.attr('id')

ajax的 get和post方法

$.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与setInterval

setTimeout 延时多少毫秒执行。

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

setInterval 延时多少毫秒循环执行

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)
该函数会在下次浏览器刷新页面之前执行一次,通常会用递归写法使其每秒执行60次func函数。调用时会传入一个参数,表示函数执行的时间戳,单位为毫秒。

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

单击取消动画效果

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与Set

Map

Map 对象保存键值对。

用for…of或者forEach可以按插入顺序遍历。
键值可以为任意值,包括函数、对象或任意基本类型。

常用API:

set(key, value):插入键值对,如果key已存在,则会覆盖原有的value
get(key):查找关键字,如果不存在,返回undefined
size:返回键值对数量
has(key):返回是否包含关键字key
delete(key):删除关键字key
clear():删除所有元素

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 对象允许你存储任何类型的唯一值,无论是原始值或者是对象引用。

用for…of或者forEach可以按插入顺序遍历。
常用API:

add():添加元素
has():返回是否包含某个元素
size:返回元素数量
delete():删除某个元素
clear():删除所有元素

   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

可以在用户的浏览器上存储键值对。

常用API:

setItem(key, value):插入
getItem(key):查找
removeItem(key):删除
clear():清空

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

1.11.6 JSON

JSON对象用于序列化对象、数组、数值、字符串、布尔值和null。

常用API:

JSON.parse():将字符串解析成对象
JSON.stringify():将对象转化为字符串

    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 日期

返回值为整数的API,数值为1970-1-1 00:00:00 UTC(世界标准时间)到某个时刻所经过的毫秒数:

与Date对象的实例相关的API:

new Date():返回现在时刻。
new Date(“2022-04-15T15:30:00.000+08:00”):返回北京时间2022年4月15日 15:30:00的时刻。
两个Date对象实例的差值为毫秒数
getDay():返回星期,0表示星期日,1-6表示星期一至星期六
getDate():返回日,数值为1-31
getMonth():返回月,数值为0-11
getFullYear():返回年份
getHours():返回小时
getMinutes():返回分钟
getSeconds():返回秒
getMilliseconds():返回毫秒

1.11.8 WebSocket

与服务器建立全双工连接。

常用API:

new WebSocket(‘ws://localhost:8080’);:建立ws连接。
send():向服务器端发送一个字符串。一般用JSON将传入的对象序列化为字符串。
onopen:类似于onclick,当连接建立时触发。
onmessage:当从服务器端接收到消息时触发。
close():关闭连接。
onclose:当连接关闭后触发。

1.11.9 window

window.open(“https://www.acwing.com”)在新标签栏中打开页面。
location.reload()刷新页面。
location.href = “https://www.acwing.com”:在当前标签栏中打开页面。

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

Canvas 教程

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

其他

来源:Acwing

猜你喜欢

转载自blog.csdn.net/shizheng_Li/article/details/128505024
今日推荐