Correcting teacher:PHPz
Correction status:qualified
Teacher's comments:完成的很好, 没什么问题, 继续加油
类声明
let User = class {
构造函数:声明属性
constructor(uname, email) {
(1) 属性
this.uname = uname
this.email = email
}
(2) 方法
say() {
return `${this.uname}: ( ${this.email} )`
}
(3) 静态成员
static nation = 'CHINA'
}
类的实例化
const user = new User('王小二', 'wang@qq.com')
console.log(user.say())
console.log(User.nation)
继承
class Child extends User {
constructor(uname, email, sex) {
// super 调用父类成员
super(uname, email)
// 子类扩展的属性
this.sex = sex
}
say() {
// super.say() 父类中的say()
return `${super.say()}, (${this.sex})`
}
}
const child = new Child('仙女', 'xn@qq.com', '女')
console.log(child.say())
! 在类中使用"访问器属性"
const Stu = class {
#age = 18
get age() {
return this.#age
}
set age(age) {
if (age >= 18 && age <= 100) {
this.#age = age
} else {
console.log('年龄必须在18-100之间')
}
}
}
let stu = new Stu()
console.log('age = ', stu.age)
// stu.age = 120
stu.age = 30
console.log('age = ', stu.age)
实例演示字符串,数组常用API
数组 API -1
包括对象在内, 尽量只用字面量来声明
let arr = [1, 2, 'a', 'b', true, { x: 1, y: 2 }, [1, 2, 3], function () {}]
console.log(arr)
…rest 压缩与展开
arr = [1, 2, 3]
let arr1 = [...arr]
console.log(arr1)
arr = [...arr, 4, 5, 6]
console.log(arr)
console.log('--------------------')
Array.of 打包
let items = [1, 2, 3, 4, 5, 6]
console.log(Array.of(...items))
Array.from(): 类数组(对象) -> 包装成一个真正的数组
const likeArr = {
0: 'red',
1: 'blue',
2: 'green',
length: 3,
}
为什么要转为真数组?
因为数组上有非常多的方法可以使用
const data = Array.from(likeArr)
console.log(Array.isArray(data) ? 'Array' : 'No Array')
for (let item of data) {
console.log(item)
}