js使用方式
Javascript有两种使用方式:
第一种, 直接在
<script>标签中写:<script type="module"> /* js代码 */ </script>
第二种, 首先在js源文件中用
export暴露, 然后在<script>中引入.let name = "LiGaOg"; function haha() { } export { name, haha };然后在html中引入:
<script type="module"> import { name, haha } from "源文件路径" </script>
js的变量
变量有数值, 字符串, 布尔值, 对象和undefined, 定义方式如下:
let a = 1;
let b = "haha";
let c = {
name: "haha",
age: 18,
};
其中, 对象的访问方式有两种:
let person = {
name: "hh",
age: 18,
add: function() {
}
};
// 第一种
person["name"], person["add"]()
// 第二种
person.name, person.add()
js的运算符
与其他语言类似, 不同点在于:
- js的乘方运算是
**. - js判断相等和不相等是
===和!==. - js中除法
/不是默认向下取整, 而是得到浮点数, 如果需要向下取整可以在/之后用parseInt.
js的输出输出
输出可以用
console.log().格式化字符串:
let name = "LiGaOg"; let age = 11; let formatString = `My name is ${name}, with age ${age}`;定义多行字符串:
let s = ` <div> <h1>Title</h1> </div> `保留n位小数输出:
let x = 1.14514; let s = `${x.toFixed(2)}`js写算法题的输入输出, 用如下代码框架:
let buf = ""; process.stdin.on("readable", function() { let chunk = process.stdin.read(); if (chunk) buf += chunk.toString(); }); process.stdin.on("end", function() { /* 之后, buf就存储从stdin读入的东西 */ });如果输入是这种格式:
3 4, 可以这样写:```javascript
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);
});
## js循环语句
* `for`循环:
```javascript
for (let i = 0; i < 10; i ++) {
}
// 遍历数组的值
for (let value of array) {
console.log(value);
}
js常用的数学API
Math.round(x): 向0取整Math.ceil(x): 向上取整Math.floor(x): 向下取整
js数组
数组定义如下, 数组中的元素可以是不同类型:
let a = [1, "name", function() add {}, {name: 1, age: 2}];
数组常用api:
length: 长度.push(): 向末尾添加元素.pop(): 弹出末尾的元素.splice(a, b): 返回一个数组, 由从a开始的b个元素组成.a.sort(cmp): 将数组从小到大排序, 可以自定义比较函数.a.sort(function(a, b) { return a - b; });
js的面向对象
定义
js的Class和其他语言类似, 但是不存在private的成员变量.
Class的定义框架如下:
class Person {
// 构造函数
constructor(name, age) {
this.name = name;
this.age = age;
}
// 成员函数
init() {
}
toString() {
this.init();
}
}
继承与多态
继承关系用extends定义:
class LiGaOg extends Person {
constructor(name, age, haha) {
super(name, age);
this->haha = haha;
}
toString() {
return super.toString();
}
}
注意:
- 子类只有调用父类构造函数之后, 才可以用
this. super既可以当函数用, 也可以当变量用.- 当函数用, 表示调用父类的构造函数
super(). - 当变量用, 指向父类原型, 可以调用父类的成员函数
super.toString().
- 当函数用, 表示调用父类的构造函数
- 子类成员与父类重名时, 以子类为主, 即多态.
静态变量和函数
定义访问静态变量
class Point { constructor(x, y) { this.x = x; this.y = y; // 静态变量 Point.cnt ++; } } console.log(Point.cnt);定义静态函数: 在成员函数前面加
staticclass Point { constructor(x, y) { this.x = x; this.y = y; // 静态变量 Point.cnt ++; } static toString() { } } Point.toString();
js事件
js代码的执行一般通过事件驱动, 事件api是addEventListener, 代码框架是:
/* a在实战时, 一般是DOM对象 */
a.addEventListener("事件名称", function(e) {
/* 根据事件变量e进行处理 */
});