TypeScript简写为“if”

问题描述 投票:1回答:2

我是初学Web开发人员。抱歉,我不擅长英语。

export class Vector{
    protected x : number = 0
    protected y : number = 0
    protected z : number = 0

    set(x?: number , y? : number , z? : number){
        this.x = x ? x : this.x
        this.y = y ? y : this.y
        this.z = z ? z : this.z
    }
}

我想从“this.x = x?x:this.x”中删除“:this.x”

我想写一下,我想删除其他部分。

set(x?: number , y? : number , z? : number){
    if(x){
      this.x = x
    }
}

我不想这样写。因为它不酷。任何人请告诉我写这段代码的好方法。

- 加 - -

我想做的是这样的事情。

set(x?: number , y? : number , z? : number){
            this.x = x ? x : DO NOTHING(WRITE NOTHNG)
        }

---------- Lars Holdaas ---------- enter image description here

这里!在平等!说“;”是必须的。

javascript typescript
2个回答
2
投票

通常x && this.x=x将是完成此任务的最短语法。

但是x,y和z都是数字。将这种简短的语法用于数字有点危险。考虑使用x = 0调用set的情况。 0 && this.x=x不会执行this.x,因为0在Javascript中是假的。通过阅读代码,这似乎不是您想要实现的,而是在x未定义的情况下,您希望跳过设置this.x.

在这种情况下,我建议以下代码:

set(x?: number , y? : number , z? : number){
    typeof x === 'number' && (this.x = x);
    typeof y === 'number' && (this.y = y);
    typeof z === 'number' && (this.z = z);
}

这样你的set函数将支持发送0作为参数,它目前没有。


1
投票

编写方法的一种干净方法是

set(x?: number , y? : number , z? : number){
  this.x = x || this.x;
  this.y = y || this.y;
  this.z = z || this.z;
}

另一种方式是

set(x?: number , y? : number , z? : number){
  x && this.x = x;
  y && this.y = y;
  z && this.z = z;
}

但是,正如@Lars Holdaas已经提到的那样,这将不支持虚假值(如0"")。解决此问题的一般方法是编写验证或过滤函数,以判断该值是否真正适用于该参数。

// returns `true` if x is a number
const n = x => typeof n === 'number';

set(x?: number , y? : number , z? : number){
  n(x) && this.x = x;
  n(y) && this.y = y;
  n(z) && this.z = z;
}

希望这可以帮助 :)

© www.soinside.com 2019 - 2024. All rights reserved.