Blogger Information
Blog 26
fans 0
comment 1
visits 10492
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
1. 实例演示class类与extends,super等的用法 2. 实例演示字符串,数组常用API
P粉751989631
Original
316 people have browsed it
  1. 实例演示class类与extends,super等的用法
  2. 类声明

    1. let User = class {
    2. 构造函数:声明属性
    3. constructor(uname, email) {
    4. (1) 属性
    5. this.uname = uname
    6. this.email = email
    7. }
    8. (2) 方法
    9. say() {
    10. return `${this.uname}: ( ${this.email} )`
    11. }
    12. (3) 静态成员
    13. static nation = 'CHINA'
    14. }
  3. 类的实例化

  1. const user = new User('王小二', 'wang@qq.com')
  2. console.log(user.say())
  3. console.log(User.nation)
  4. 继承
  5. class Child extends User {
  6. constructor(uname, email, sex) {
  7. // super 调用父类成员
  8. super(uname, email)
  9. // 子类扩展的属性
  10. this.sex = sex
  11. }
  12. say() {
  13. // super.say() 父类中的say()
  14. return `${super.say()}, (${this.sex})`
  15. }
  16. }
  17. const child = new Child('仙女', 'xn@qq.com', '女')
  18. console.log(child.say())
  19. ! 在类中使用"访问器属性"
  20. const Stu = class {
  21. #age = 18
  22. get age() {
  23. return this.#age
  24. }
  25. set age(age) {
  26. if (age >= 18 && age <= 100) {
  27. this.#age = age
  28. } else {
  29. console.log('年龄必须在18-100之间')
  30. }
  31. }
  32. }
  33. let stu = new Stu()
  34. console.log('age = ', stu.age)
  35. // stu.age = 120
  36. stu.age = 30
  37. console.log('age = ', stu.age)

运行结果

  1. 实例演示字符串,数组常用API
    数组 API -1
    包括对象在内, 尽量只用字面量来声明

    1. let arr = [1, 2, 'a', 'b', true, { x: 1, y: 2 }, [1, 2, 3], function () {}]
    2. console.log(arr)

    …rest 压缩与展开

    1. arr = [1, 2, 3]
    2. let arr1 = [...arr]
    3. console.log(arr1)
    4. arr = [...arr, 4, 5, 6]
    5. console.log(arr)
    6. console.log('--------------------')

    Array.of 打包

    1. let items = [1, 2, 3, 4, 5, 6]
    2. console.log(Array.of(...items))

    Array.from(): 类数组(对象) -> 包装成一个真正的数组

    1. const likeArr = {
    2. 0: 'red',
    3. 1: 'blue',
    4. 2: 'green',
    5. length: 3,
    6. }

    为什么要转为真数组?
    因为数组上有非常多的方法可以使用

  1. const data = Array.from(likeArr)
  2. console.log(Array.isArray(data) ? 'Array' : 'No Array')
  3. for (let item of data) {
  4. console.log(item)
  5. }

运行结果

Correcting teacher:PHPzPHPz

Correction status:qualified

Teacher's comments:完成的很好, 没什么问题, 继续加油
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post