javascript - TypeScript 简单写下 "if"

标签 javascript typescript

我是初学者网络开发人员。 我英语不好,抱歉。

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)
        }

----------致拉尔斯·霍尔达斯---------- enter image description here

这里!平等之下! 说“;”是必需的。

最佳答案

通常 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 作为参数,但目前尚不支持。

关于javascript - TypeScript 简单写下 "if",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52095532/

相关文章:

javascript - 即使没有订阅,Observable 内的 http 请求也会发生

javascript - Typescript 数组语法 MyModel[] 或 [MyModel]

angular - 无法使用 Karma 和 Jasmine 测试 Angular http 拦截器

javascript - 我可以在 JS 项目中使用 TS 库吗?

javascript - Jquery - 在一个大验证器方法中调用多个验证器

javascript - node.js 全局数组与 redis

javascript - 从模块内的函数更新全局变量

javascript - REACT 删除对象数组中的元素

reactjs - 属性 'setLink' 在类型 'ApolloClient<NormalizedCacheObject>' 中缺失,但在类型 'ApolloClient<any> 中需要

arrays - 如何在 TypeScript 中定义具有交替类型的数组?