zsydgithub 1 year ago
parent
commit
1828de78e0
7 changed files with 479 additions and 0 deletions
  1. 37 0
      Ts-泛型/1_泛型.js
  2. 40 0
      Ts-泛型/1_泛型.ts
  3. 119 0
      Ts-泛型/2_例题.js
  4. 131 0
      Ts-泛型/2_例题.ts
  5. 72 0
      Ts-泛型/tsconfig.json
  6. 13 0
      Ts-泛型/页面.html
  7. 67 0
      题目.html

+ 37 - 0
Ts-泛型/1_泛型.js

@@ -0,0 +1,37 @@
+//指在定义函数、接口、类的时候,不与先执行具体的类型,而是在使用的时候再去指定的一种特性
+(function () {
+    //创建一个函数,根据指定数量的count和数据value创建一个包含count个value的数组
+    // function creatArray(count: number, value: any): any[] {
+    //   const arr: any[] = []
+    //   for (let i = 0; i < count; i++) {
+    //     arr.push(value)
+    //   }
+    //   return arr
+    // }
+    // const arr1 = creatArray(4, 11)
+    // const arr2 = creatArray(6, 'aa')
+    // console.log(arr1[0].toFixed())
+    // console.log(arr2[0].split(''))
+    function creatArray2(count, value) {
+        var arr = [];
+        for (var i = 0; i < count; i++) {
+            arr.push(value);
+        }
+        return arr;
+    }
+    var arr3 = creatArray2(11, 3);
+    console.log(arr3);
+    var arr4 = creatArray2(4, 'cc');
+    console.log(arr4);
+    // console.log(arr3[0].toFixed())
+    // console.log(arr3[0].split(''))
+    // console.log(arr4[0].split(''))
+    // console.log(arr4[0].toFixed())
+    //多个泛型参数的函数
+    function swap(a, b) {
+        return [a, b];
+    }
+    var result = swap('abc', 123);
+    console.log(result);
+    console.log(result[0].length, result[1].toFixed());
+})();

+ 40 - 0
Ts-泛型/1_泛型.ts

@@ -0,0 +1,40 @@
+//指在定义函数、接口、类的时候,不与先执行具体的类型,而是在使用的时候再去指定的一种特性
+(() => {
+  //创建一个函数,根据指定数量的count和数据value创建一个包含count个value的数组
+  // function creatArray(count: number, value: any): any[] {
+  //   const arr: any[] = []
+  //   for (let i = 0; i < count; i++) {
+  //     arr.push(value)
+  //   }
+  //   return arr
+  // }
+  // const arr1 = creatArray(4, 11)
+  // const arr2 = creatArray(6, 'aa')
+  // console.log(arr1[0].toFixed())
+  // console.log(arr2[0].split(''))
+
+  function creatArray2<T>(count: number, value: T) {
+    const arr: Array<T> = []
+    for (let i = 0; i < count; i++) {
+      arr.push(value)
+    }
+    return arr
+  }
+  const arr3 = creatArray2<number>(11,3)
+  console.log(arr3)
+  const arr4 = creatArray2<string>(4,'cc')
+  console.log(arr4)
+  // console.log(arr3[0].toFixed())
+  // console.log(arr3[0].split(''))
+  // console.log(arr4[0].split(''))
+  // console.log(arr4[0].toFixed())
+
+
+  //多个泛型参数的函数
+  function swap<K,V>(a:K,b:V): [K,V] {
+    return[a,b]
+  }
+  const result = swap<string,number>('abc',123)
+  console.log(result)
+  console.log(result[0].length,result[1].toFixed())
+})()

+ 119 - 0
Ts-泛型/2_例题.js

@@ -0,0 +1,119 @@
+(function () {
+    /*
+    定义一个接口,接口中有3个抽象方法如下。
+    (1)“fact(m:number):number;”方法的功能为求参数的阶乘。
+    (2)“intPower(m:number,n:number):number;”方法的功能为求参数m的n次方。
+    (3)“findFactor(m:number,n:number):boolean;”方法的功能为判断参数m加上参数n的和是否大于100。
+    */
+    /* interface ITest {
+      fact(m: number): number
+      intPower(m: number, n: number): number
+      findFactor(m: number, n: number): boolean
+    }
+  
+    class Realize implements ITest {
+      fact(m: number): number {
+        let sum = 1
+        for (let i = 1; i <= m; i++) {
+          sum = sum * i
+        }
+        return sum
+      }
+      intPower(m: number, n: number): number {
+        return Math.pow(m,n)
+      }
+      findFactor(m: number, n: number): boolean {
+        if( m + n > 100){
+          return true
+        } else {
+          return false
+        }
+      }
+    }
+    let r1 = new Realize()
+    console.log(r1.fact(6))
+    console.log(r1.intPower(4,2))
+    console.log(r1.findFactor(50,60)) */
+    /*
+    创建一个接口IShape,接口中有一个求面积的方法“getArea()”和求周长的方法“getLength()”。
+    定义一个正方形类Square,该类实现了IShape接口。Square类中有一个属性a表示正方形的边长,在构造方法中初始化该边长。
+    创建Square类的实例对象,求该正方形对象的面积和周长
+    */
+    /* interface Ishape{
+      getArea(): number
+      getLength(): number
+    }
+  
+    class Square implements Ishape{
+      a: number
+      constructor(a: number){
+        this.a = a
+      }
+      getArea(): number {
+        return Math.pow(this.a,2)
+      }
+      getLength(): number {
+        return 4*this.a
+      }
+    }
+    let square = new Square(5)
+    console.log('正方形的面积为'+ square.getArea())
+    console.log('正方形的周长为'+ square.getLength()) */
+    /* interface Person{
+      eat(): void
+      sleep(): void
+    }
+    class Student implements Person{
+      eat(): void {
+        console.log('学生去食堂吃饭')
+      }
+      sleep(): void {
+        console.log('学生去宿舍睡觉')
+      }
+    }
+    class Teacher implements Person{
+      eat(): void {
+        console.log('老师去教室食堂吃饭')
+      }
+      sleep(): void {
+        console.log('老师去学校公寓睡觉')
+      }
+    }
+    class Parent implements Person{
+      eat(): void {
+        console.log('家长去招待所吃饭')
+      }
+      sleep(): void {
+        console.log('家长去招待所睡觉')
+      }
+    }
+  
+  
+    let stu1 = new Student()
+    let tea1 = new Teacher()
+    let par1 = new Parent()
+  
+    stu1.eat()
+    stu1.sleep()
+  
+    tea1.eat()
+    tea1.sleep()
+  
+    par1.eat()
+    par1.sleep() */
+    /*
+    定义墨盒接口InkBox,约定墨盒的颜色。 定义纸张接口Paper,约定纸张的大小。 定义打印机类,引用墨盒接口、纸张接口实现打印功能。
+    墨盒厂商按照InkBox接口实现ColorInkBox类和GrayInkBox类。
+  纸张厂商按照Paper接口实现A4Paper类和B5Paper类。“组装”打印机,让打印机通过不同的墨盒和纸张实现打印功能。
+  
+    程序运行效果如下:
+  
+  使用黑白墨盒在A4纸上打印。
+  
+  使用黑白墨盒在B5纸上打印。
+  
+  使用彩色墨盒在A4纸上打印。
+  
+  使用彩色墨盒在B5纸上打印。
+    */
+})();

+ 131 - 0
Ts-泛型/2_例题.ts

@@ -0,0 +1,131 @@
+(() => {
+  /* 
+  定义一个接口,接口中有3个抽象方法如下。
+  (1)“fact(m:number):number;”方法的功能为求参数的阶乘。
+  (2)“intPower(m:number,n:number):number;”方法的功能为求参数m的n次方。
+  (3)“findFactor(m:number,n:number):boolean;”方法的功能为判断参数m加上参数n的和是否大于100。
+  */
+
+
+  /* interface ITest {
+    fact(m: number): number
+    intPower(m: number, n: number): number
+    findFactor(m: number, n: number): boolean
+  }
+
+  class Realize implements ITest {
+    fact(m: number): number {
+      let sum = 1
+      for (let i = 1; i <= m; i++) {
+        sum = sum * i
+      }
+      return sum
+    }
+    intPower(m: number, n: number): number {
+      return Math.pow(m,n)
+    }
+    findFactor(m: number, n: number): boolean {
+      if( m + n > 100){
+        return true
+      } else {
+        return false
+      }
+    }
+  }
+  let r1 = new Realize()
+  console.log(r1.fact(6))
+  console.log(r1.intPower(4,2))
+  console.log(r1.findFactor(50,60)) */
+
+
+/* 
+创建一个接口IShape,接口中有一个求面积的方法“getArea()”和求周长的方法“getLength()”。
+定义一个正方形类Square,该类实现了IShape接口。Square类中有一个属性a表示正方形的边长,在构造方法中初始化该边长。
+创建Square类的实例对象,求该正方形对象的面积和周长
+*/
+
+  /* interface Ishape{
+    getArea(): number
+    getLength(): number
+  }
+
+  class Square implements Ishape{
+    a: number
+    constructor(a: number){
+      this.a = a
+    }
+    getArea(): number {
+      return Math.pow(this.a,2)
+    }
+    getLength(): number {
+      return 4*this.a
+    }
+  }
+  let square = new Square(5)
+  console.log('正方形的面积为'+ square.getArea())
+  console.log('正方形的周长为'+ square.getLength()) */
+
+
+
+  /* interface Person{
+    eat(): void
+    sleep(): void
+  }
+  class Student implements Person{
+    eat(): void {
+      console.log('学生去食堂吃饭')
+    }
+    sleep(): void {
+      console.log('学生去宿舍睡觉')
+    }
+  }
+  class Teacher implements Person{
+    eat(): void {
+      console.log('老师去教室食堂吃饭')
+    }
+    sleep(): void {
+      console.log('老师去学校公寓睡觉')
+    }
+  }
+  class Parent implements Person{
+    eat(): void {
+      console.log('家长去招待所吃饭')
+    }
+    sleep(): void {
+      console.log('家长去招待所睡觉')
+    }
+  }
+
+
+  let stu1 = new Student()
+  let tea1 = new Teacher()
+  let par1 = new Parent()
+
+  stu1.eat()
+  stu1.sleep()
+
+  tea1.eat()
+  tea1.sleep()
+
+  par1.eat()
+  par1.sleep() */
+
+
+
+
+  /* 
+  定义墨盒接口InkBox,约定墨盒的颜色。 定义纸张接口Paper,约定纸张的大小。 定义打印机类,引用墨盒接口、纸张接口实现打印功能。 
+  墨盒厂商按照InkBox接口实现ColorInkBox类和GrayInkBox类。 
+纸张厂商按照Paper接口实现A4Paper类和B5Paper类。“组装”打印机,让打印机通过不同的墨盒和纸张实现打印功能。
+
+  程序运行效果如下:
+
+使用黑白墨盒在A4纸上打印。
+
+使用黑白墨盒在B5纸上打印。
+
+使用彩色墨盒在A4纸上打印。
+
+使用彩色墨盒在B5纸上打印。
+  */
+})()

+ 72 - 0
Ts-泛型/tsconfig.json

@@ -0,0 +1,72 @@
+{
+  "compilerOptions": {
+    /* Visit https://aka.ms/tsconfig.json to read more about this file */
+
+    /* Basic Options */
+    // "incremental": true,                         /* Enable incremental compilation */
+    "target": "es5",                                /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', 'ES2021', or 'ESNEXT'. */
+    "module": "commonjs",                           /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */
+    // "lib": [],                                   /* Specify library files to be included in the compilation. */
+    // "allowJs": true,                             /* Allow javascript files to be compiled. */
+    // "checkJs": true,                             /* Report errors in .js files. */
+    // "jsx": "preserve",                           /* Specify JSX code generation: 'preserve', 'react-native', 'react', 'react-jsx' or 'react-jsxdev'. */
+    // "declaration": true,                         /* Generates corresponding '.d.ts' file. */
+    // "declarationMap": true,                      /* Generates a sourcemap for each corresponding '.d.ts' file. */
+    // "sourceMap": true,                           /* Generates corresponding '.map' file. */
+    // "outFile": "./",                             /* Concatenate and emit output to single file. */
+    // "outDir": "./",                              /* Redirect output structure to the directory. */
+    // "rootDir": "./",                             /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
+    // "composite": true,                           /* Enable project compilation */
+    // "tsBuildInfoFile": "./",                     /* Specify file to store incremental compilation information */
+    // "removeComments": true,                      /* Do not emit comments to output. */
+    // "noEmit": true,                              /* Do not emit outputs. */
+    // "importHelpers": true,                       /* Import emit helpers from 'tslib'. */
+    // "downlevelIteration": true,                  /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
+    // "isolatedModules": true,                     /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */
+
+    /* Strict Type-Checking Options */
+    "strict": false,                                 /* Enable all strict type-checking options. */
+    // "noImplicitAny": true,                       /* Raise error on expressions and declarations with an implied 'any' type. */
+    // "strictNullChecks": true,                    /* Enable strict null checks. */
+    // "strictFunctionTypes": true,                 /* Enable strict checking of function types. */
+    // "strictBindCallApply": true,                 /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
+    // "strictPropertyInitialization": true,        /* Enable strict checking of property initialization in classes. */
+    // "noImplicitThis": true,                      /* Raise error on 'this' expressions with an implied 'any' type. */
+    // "alwaysStrict": true,                        /* Parse in strict mode and emit "use strict" for each source file. */
+
+    /* Additional Checks */
+    // "noUnusedLocals": true,                      /* Report errors on unused locals. */
+    // "noUnusedParameters": true,                  /* Report errors on unused parameters. */
+    // "noImplicitReturns": true,                   /* Report error when not all code paths in function return a value. */
+    // "noFallthroughCasesInSwitch": true,          /* Report errors for fallthrough cases in switch statement. */
+    // "noUncheckedIndexedAccess": true,            /* Include 'undefined' in index signature results */
+    // "noImplicitOverride": true,                  /* Ensure overriding members in derived classes are marked with an 'override' modifier. */
+    // "noPropertyAccessFromIndexSignature": true,  /* Require undeclared properties from index signatures to use element accesses. */
+
+    /* Module Resolution Options */
+    // "moduleResolution": "node",                  /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
+    // "baseUrl": "./",                             /* Base directory to resolve non-absolute module names. */
+    // "paths": {},                                 /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
+    // "rootDirs": [],                              /* List of root folders whose combined content represents the structure of the project at runtime. */
+    // "typeRoots": [],                             /* List of folders to include type definitions from. */
+    // "types": [],                                 /* Type declaration files to be included in compilation. */
+    // "allowSyntheticDefaultImports": true,        /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
+    "esModuleInterop": true,                        /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
+    // "preserveSymlinks": true,                    /* Do not resolve the real path of symlinks. */
+    // "allowUmdGlobalAccess": true,                /* Allow accessing UMD globals from modules. */
+
+    /* Source Map Options */
+    // "sourceRoot": "",                            /* Specify the location where debugger should locate TypeScript files instead of source locations. */
+    // "mapRoot": "",                               /* Specify the location where debugger should locate map files instead of generated locations. */
+    // "inlineSourceMap": true,                     /* Emit a single file with source maps instead of having a separate file. */
+    // "inlineSources": true,                       /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */
+
+    /* Experimental Options */
+    // "experimentalDecorators": true,              /* Enables experimental support for ES7 decorators. */
+    // "emitDecoratorMetadata": true,               /* Enables experimental support for emitting type metadata for decorators. */
+
+    /* Advanced Options */
+    "skipLibCheck": true,                           /* Skip type checking of declaration files. */
+    "forceConsistentCasingInFileNames": true        /* Disallow inconsistently-cased references to the same file. */
+  }
+}

+ 13 - 0
Ts-泛型/页面.html

@@ -0,0 +1,13 @@
+<!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>
+</head>
+<body>
+  <!-- <script src="./1_泛型.js"></script> -->
+  <script src="./2_例题.js"></script>
+</body>
+</html>

+ 67 - 0
题目.html

@@ -0,0 +1,67 @@
+<!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>
+</head>
+<body>
+  定义一个接口,接口中有3个抽象方法如下。
+
+(1)“fact(m:number):number;”方法的功能为求参数的阶乘。
+
+(2)“intPower(m:number,n:number):number;”方法的功能为求参数m的n次方。
+
+(3)“findFactor(m:number,n:number):boolean;”方法的功能为判断参数m加上参数n的和是否大于100。
+
+
+
+
+
+创建一个接口IShape,接口中有一个求面积的方法“getArea()”和求周长的方法“getLength()”。
+
+定义一个正方形类Square,该类实现了IShape接口。Square类中有一个属性a表示正方形的边长,在构造方法中初始化该边长。
+创建Square类的实例对象,求该正方形对象的面积和周长
+
+
+
+
+编写一个学校接待方面的程序(招待不同身份的人的食宿问题),其对应规则如下:用接口实现
+
+身份      食          住宿
+学生      食堂        宿舍
+教师      教师食堂    学校公寓
+学生家长   招待所     招待所
+
+
+学生去食堂吃饭! 
+
+学生回寝室睡觉! 
+
+教师去教工餐厅吃饭! 
+
+教师回学校公寓睡觉! 
+
+家长去招待所饭馆吃饭! 
+
+家长回招待所睡觉
+
+
+
+
+
+定义墨盒接口InkBox,约定墨盒的颜色。 定义纸张接口Paper,约定纸张的大小。 定义打印机类,引用墨盒接口、纸张接口实现打印功能。 墨盒厂商按照InkBox接口实现ColorInkBox类和GrayInkBox类。 
+纸张厂商按照Paper接口实现A4Paper类和B5Paper类。“组装”打印机,让打印机通过不同的墨盒和纸张实现打印功能。
+
+   程序运行效果如下:
+
+使用黑白墨盒在A4纸上打印。
+
+使用黑白墨盒在B5纸上打印。
+
+使用彩色墨盒在A4纸上打印。
+
+使用彩色墨盒在B5纸上打印。
+</body>
+</html>