「极速上手TypeScript」TypeScript进阶“对象”

[TOC]

一、定义

在TS中,我们定义一个对象不需要‘类’也不需要‘机构体’,如果我们需要写一个对象就可直接写,下面我们来看看:

//对象,直接建立对象即可
//定义对象em1
const em1 = {
 name: 'join', 
 gendr: 'male',
 salary: 8000,
 bonus: undefined  //bonus暂时不给值
 performance:5.5,
}console.log(em1)

就这样,一个简单的对象我们就定义好了,看看打印结果:

 "name": "join",
 "gendr": "male",
 "salary": 8000,
 "bonus": undefined,
 "performance": 5.5

下面我们再来看看里面的一些细节:

  1. 指定类型:

    在上面例子中,我们的性别不一定是male,可以是female、other、unknown , 所以可以写成:

    gendr: 'male' as ('male' | 'female' | 'other' | 'unknown'),

    当我们在赋值时也就只能赋值里面指定的类型

  2. undefined:

    我们在上面例子中:

    bonus: undefined

    这里使用undefined相当于没写这行,此时我们不能给bonus直接赋值,这里仍然需要这样写:

    bonus: undefined as (number| undefined),//当然也可以写其他类型

    下面我们来看一个小例子:

    const em1 = {
    name: 'join',
    gendr: 'male' as ('male' | 'female' | 'other' | 'unknown'),
    salary: 8000,
    bonus: undefined as (number| undefined),
    performance:5.5,
    }
    ​
    ​
    console.log(`${em1.name} has a salary of ${em1.salary}`)
    //判断是否发奖金
    if (!em1.bonus){   //显然bonus没有给值,走if分支
     em1.bonus = em1.salary * em1.performance
     console.log(em1.bonus)
    }else{
     console.log('already for the bonus')
    }

    二、 嵌套

对象可以嵌套对象,也可以嵌套,对象也可以嵌套数组

  1. 对象嵌套对象
    const em1 = {
     //对象嵌套对象
     name : {
     first:'三',
     last: '张',
     },
     gendr: 'male' as ('male' | 'female' | 'other' | 'unknown'),
     salary: 8000,
     bonus: undefined as (number| undefined),
     performance:5.5,
    }console.log(em1)  //打印
    打印结果:
    {
     "name": {
     "first": "三",
     "last": "张"
     },
     "gendr": "male",
     "salary": 8000,
     "bonus": 44000,
     "performance": 5.5,
    }
  2. 对象嵌套数组
    const em1 = {
     //结构体套结构体
     name : {
     first:'三',
     last: '张',
     },
     gendr: 'male' as ('male' | 'female' | 'other' | 'unknown'),
     salary: 8000,
     bonus: undefined as (number| undefined),
     performance:5.5,
     badges: ['优先员工','迟到王'],   //string[……]
    }

    三、JSON(stringify/parse)的应用

我们可以使用json将对象转换为json格式(是一种网络传输字符格式),也可以将字符串转换为对象

  1. 将对象转换为字符串

    const em1 = {
     //结构体套结构体
     name : {
     first:'三',
     last: '张',
     },
     gendr: 'male' as ('male' | 'female' | 'other' | 'unknown'),
     salary: 8000,
     bonus: undefined as (number| undefined),
     performance:5.5,
     badges: ['优先教师','迟到王'],   //string[……]
    }
    ​
    
    console.log('将对象转为字符串')
    const s: string = JSON.stringify(em2)   //JSON.stringify()  对象转为字符串
    console.log(s)

    看看打印结果:

    "{"name":{"first":"","last":""},"gendr":"male","salary":8000,"bonus":44000,"performance":5.5,"badges":["优先教师","迟到王"]}"
  2. 将字符串转换为对象

    (连接上段代码)

    console.log('将字符串转为对象')
    const em3 = JSON.parse(s)
    console.log(em3)

    打印结果:

    {
     "name": {
     "first": "三",
     "last": "张"
     },
     "gendr": "male",
     "salary": 8000,
     "bonus": 44000,
     "performance": 5.5,
     "badges": [
     "优先教师",
     "迟到王"
     ]
    } 

    四、函数

    其实函数我们在基础语法的时候就已经遇见了,但我们只做了简单介绍,下面我们来具体讲解一下TS的函数:

    1. 函数的定义

      定义一个加法的函数
      
      function add(a: number, b: number){
       console.log(a + b) //打印结果
      }
      //一个简单的加法函数就定义好了
      //调用:
      add(100, 100) //输出结果:200

      在函数中’a’和‘b’都是形参(形式参数),而我们在调用时的具体数据为实参(实际参数)

      我们继续深入,上面的函数是没有返回值的,再来定义一个有返回值的函数:

      function add(a: number, b: number):number{  //参数列表后面这需要加冒号及返回值类型
       return a + b
      }
      //调用:
      const num = add(100, 100)
      console.log(num)  //输出:200
  3. 可选参数/默认参数/可变参数列表

    可选参数:当我们在定义和使用函数时,有时需要多个参数,有时候参数有需要的少一些,例如:我们要一个既可以计算2个数有可以计算3个数的函数,这是候就需要可选参数,下面来定义一个有可选参数的函数:

    function add(a: number, b: number, c?: number):number{ //使用’?‘表示可选参数
    if(c){
     return a + b + c
    } else{
     return a + b
     }
    }
    //调用:
    console.log(add(100, 100, 100))  //输出:300
    console.log(add(100, 100))       //输出:200

    其实在add函数结构中还有更简单的语法:

    //method1
    function add(a: number, b: number, c?: number):number{
    return c ? a + b + c : a + b
    }//method2
    function add(a: number, b: number, c?: number):number{
    return a + b + (c||0) 
    }

    默认参数:我们在函数定义时就将某些参数设值

可变参数列表:

function add(a:number, 
    b: number, 
    c?:number,
    d: number=0, //默认参数
     ...e:number[]):number{ //不能直接return a + b + c   c 可能是undefined
     let sum = a + b + (c||0) + d
     for(let i = 0; i < e.length; i++){
         sum = sum + e[i]
     }
     return sum
}
  1. 使用对象类型作为参数

    在定义函数的时候,如果我们需要的参数较多,例如下面:

    function sendRequest(
     url: string,
     method: 'GET' | 'POST' | 'PUT',
     header: object,
     data: string,
     requireAuth:boolean,
     retry: boolean,
     retrytimeout: number,
    ){
    return data
    }//这种函数当我们需要的参数过多时,函数在调用的时候就低效
    sendRequest(https://test.com,
     'GET',
     {contentType:'application/json'}, 
     '{"name":"join"}', 
     ture,
     ture,
     3000)
    //看吧,如果该函数在其他地方,我们就不知道这些实参究竟是什么了,比如:’true‘,’3000‘等

    下面就来看看使用对象类型作为参数:

    function sendRequest(params:{   //以对象类型作为参数
         url: string,
         method: 'GET' | 'POST' | 'PUT',
         header: object,
         data: string,
         requireAuth:boolean,
         retry: boolean,
         retrytimeout?: number,
        }){
         console.log(params)
        }//调用:
    sendRequest({
         url: 'http:www.test.com',
         method: 'GET',
         header: {
         contentionType: 'application/json',
         },
         data: '',
         requireAuth: true, 
         retry: true,
         retrytimeout: 3000,
        })
    //这样就非常直观明了

    输出结果:

    {
     "url": "http:www.test.com",
     "method": "GET",
     "header": {
     "contentionType": "application/json"
     },
     "data": "",
     "requireAuth": true,
     "retry": true,
     "retrytimeout": 3000
    } 

    五、方法

我们在’四‘中介绍了函数,下面我们就可以来介绍方法,为对象定义方法了,直接来看在TS中是如何为对象定义方法:定义方法和函数的区别是函数前面需要使用关键字function,方法则不需要,其他都一样

const em1 = {
     name: 'join',
     gendr: 'male' as ('male' | 'female' | 'other' | 'unknown'),
     salary: 8000,
     bonus: undefined as (number| undefined),
     performance:5.5,

     upDataBonus(){    //em1的方法——发奖金
         if (!em1.bonus){
             em1.bonus = em1.salary * em1.performance
             console.log(em1.bonus)
         }else{
             console.log('already for the bonus')
         } 
     },

     getSalary(){   //返回工资
         return em1.salary
     }
}//这里需要注意:当我们打印对象em1时,我们在没有调em1的方法时,它是没有打印结果的
console.log(em1)

输出结果:

{
 "name": "join",
 "gendr": "male",
 "salary": 8000,
 "bonus": undefined,
 "performance": 5.5
}

所以我们需要调用:

em1.upDataBonus()
console.log(em1.getSalary())
console.log(em1)//输出结果:
44000 
8000 
{
 "name": "join",
 "gendr": "male",
 "salary": 8000,
 "bonus": 44000,
 "performance": 5.5
}

其实这里还有问题,我们在em1的内部定义方法为什么这里还是:em1.bonus,em1.salary,em1.performance

 upDataBonus(){    //em1的方法——发奖金
     if (!em1.bonus){
             em1.bonus = em1.salary * em1.performance
             console.log(em1.bonus)
     }else{
             console.log('already for the bonus')
      } 
    },

     getSalary(){   //返回工资
         return em1.salary
 }

原因是:我们的变量会去全局找,在全局中我们肯定找不到(没有在全局中定义)

如果我们改变对象的名字岂不是要修改方法里的很多变量,更何况有点对象我们没有命名

这里的解决:使用this关键字

const em1 = {
     name: 'join',
     gendr: 'male' as ('male' | 'female' | 'other' | 'unknown'),
     salary: 8000,
     bonus: undefined as (number| undefined),
     performance:5.5,upDataBonus(){    //em1的方法——发奖金
         if (!this.bonus){
             this.bonus = this.salary * this.performance
             console.log(this.bonus)
         }else{
             console.log('already for the bonus')
         } 
   },

    getSalary(){
       return this.salary
    }
}
本作品采用《CC 协议》,转载必须注明作者和本文链接
刻意学习
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!
未填写
文章
118
粉丝
88
喜欢
173
收藏
244
排名:367
访问:2.6 万
私信
所有博文
社区赞助商